Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // More about Tuples
- // Tuples is a collection of elements. Tuples are heterogeneous data structure. i.e. they can store different kind of data type. Tuples are immutable , unlike the array in scala which is mutable. An Example of Tuple that can holds an in integer, string and a boolean value.
- val name = ( 15, "Mehedi", true) // This is tuple of type tuple3
- // In Scala the tuples can hold 22 elements . If N is a number the tuples be like 1<=N<=22. If we have increase the elements then we have to use the nested tuples. Nested Tuples are blank tuples that is used inside a tuples.
- println(name._1)
- println(name._2)
- println(name._3)
- // Pattern Matching tuples
- val (a,b,c) = ( 15, "Mehedi", true)
- println(a)
- println(b)
- println(c)
- //Iterating over a tuple : To iterate over tuple, tuple.productIterator() method is used.
- var name = (15, "chandan", true)
- // The foreach method takes a function
- // as parameter and applies it to
- // every element in the collection
- name.productIterator.foreach{i=>println(i)}
- // Converting tuple to string: Converting a tuple to a string concatenates all of its elements into a string. We use the tuple.toString() method for this
- val name = (15, "chandan", true)
- // print converted string
- println(name.toString() )
- //Swap the elements of tuple: Swapping the element of a tuple we can use tuple.swap Method.
- Example :
- // Scala program to swap tuple element
- val name = ("geeksforgeeks","gfg") // print swapped element
- println(name.swap)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement