Scala Tuple

Unlike an array or list, a tuple can hold objects with different types .These are also immutable.

Here’s a tuple that contains an Int and a String:
val tuple = (50, “Gyan”)

// Get first and second items from a tuple.
val first = tuple._1
val second = tuple._2

Scala methods can return a tuple. Let us check the below example:

package com.scala.test

object TestTuple {
def getTuple: (Int, String) = (33, “Gyan”)
def main(args: Array[String]) {
val tupleValues = getTuple
println(tupleValues._1)
println(tupleValues._2)
//We can assign the tuple results directly to variables:
val (age, name) = getTuple
println(age)
println(name)
}
}

Output:
33
Gyan
33
Gyan

Iterating over a Scala tuple

package com.scala.test

object TestTuple1 {
def main(args: Array[String]) {
val tupleValues = (5, “test”, true)
tupleValues.productIterator.foreach(println)
}

}

Output
5
test
true

Leave a Reply

Your email address will not be published. Required fields are marked *