By: | 08 Aug 2016 | Category: Scala Language Basics
Scala also provides a tuple object that combines a number of elements together. Tuples like lists are immutable, however tuples can contain any type of element. Tuples are useful in different situations such as returning multiple objects from a method.
val methodResult = ("value", error)
The actual type of tuple created depends on the number of elements it contains. For instance the type of the above tuple is Tuple2. Tuples are types of Tuple1, Tuple2, Tuple3, Tuple4 and so on.
val methodResult = Tuple2("value", error) val methodResult = Tuple3("value1", "value2", "value3")
We can create a tuple up to the imposed Scala limit of 22, after which we would need to use a collection. To access elements of the tuple we use the method ._1, ._2 and so on to access the individual elements.
Scala Iterate A Tuple
To iterate a
Tuple the method
Tuple.productIterator() can be used.
var tup = (1,2) tup.productIterator.foreach(println)
var tup = (1,2) 1 2