Tuple

A Scala tuple is a class that can contain a miscellaneous collection of elements. Tuples are heterogeneous data structure i.e is they  can hold elements of different data types and is immutable in nature. A tuple is immutable.Let N be the number of elements in a tuple. Scala currently is limited to 22 elements in a tuple, that is N should be, 1<=N<=22 , the tuple can have at most 22 elements, if the number of elements exceeds 22 then this will generate an error.The following is an example of a tuple holding an integer, a string, and the console.
object test{
def main(args: Array[String])
{
val x = (1, "hello", Console)
println(x)
val y =new Tuple3(1, "hello", Console)
println(y)
val z = (4,3,2,1)
println(z)
}
}

Scala currently  limited to 22 elements in a tuple. if the number of elements exceeds 22 then it will generate an error. We can over come with these problem by using nested tuples.

Access elements from tuple:- To access elements of a tuple t, you can use method t._1 to access the first element, t._2 to access the second, and so on. For example, the following expression computes the sum of all elements of t.
object test{
def main(args: Array[String])
{
val x = (1, "hello", Console)
println("First element is")
println(x._1)
println("Second element is")
println(x._2)
}
}
Operations on tuple
object demo {
def main(args : Array[String]){
var (a,b,c) =(15,"ravl",true)
println(a)
println(b)
println(c)
}
}

object demo {
def main(args: Array[String]){
def getUserInfo = ("Al", 42, 200.0)
val(name, age, weight) = getUserInfo
println(age)
}
}
if you only want to access some of the elements, you can ignore the others by using an underscore placeholder for the elements you want to ignore. Imagine you want to ignore the weight in our example:

val (name,age,_) = getUserInfo
val (name,_,_) = getUserInfo

Iterating over the Tuple
object Iterate {
   def main(args: Array[String]) {
      val names = ("John","Smith","Anderson","Steve","Rob")
      names.productIterator.foreach{ i =>println("Value = " + i )}
   }
}

Swapping the Tuple elements
The Tuple.swap method is used to swap the elements of the tuple.
object Swap {
   def main(args: Array[String]) {
       val id = new Tuple2(12,34)
      println("Swapped Tuple Id is:"+id.swap)
    }
}

Converting Tuple to Strings
object Demo
    def main(args: Array[String]) 
    { 
        val name = (15, "chandan", true)
        println(name.toString() ) 
    }   
} 

No comments:

Post a Comment