Advertisement
mehedi2022

Reading Material_ Tuples More

Sep 15th, 2022 (edited)
611
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.57 KB | None | 0 0
  1. // More about Tuples
  2.  
  3. // 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.
  4.  
  5. val name = ( 15, "Mehedi", true) // This is tuple of type tuple3
  6. // 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.
  7.  
  8. println(name._1)
  9. println(name._2)
  10. println(name._3)
  11.  
  12. // Pattern Matching tuples
  13. val (a,b,c) = ( 15, "Mehedi", true)
  14. println(a)
  15. println(b)
  16. println(c)
  17.  
  18. //Iterating over a tuple : To iterate over tuple, tuple.productIterator() method is used.
  19.   var name = (15, "chandan", true)
  20.          
  21.         // The foreach method takes a function
  22.         // as parameter and applies it to
  23.         // every element in the collection
  24.         name.productIterator.foreach{i=>println(i)}
  25.    
  26. // 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
  27.  
  28. val name = (15, "chandan", true)
  29.          
  30.         // print converted string
  31.         println(name.toString() )
  32.  
  33. //Swap the elements of tuple: Swapping the element of a tuple we can use tuple.swap Method.
  34. Example :
  35.  
  36. // Scala program to swap tuple element
  37.  
  38. val name = ("geeksforgeeks","gfg")  // print swapped element
  39.         println(name.swap)
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement