Tuples
Tuple is a value that contains a fixed number of elements, each
with a distinct type. Tuples are immutable. Tuples are especially handy for
returning multiple values from a method or function.
A tuple with two elements
can be created as follows:
val ingredient = ("Sugar"
, 25)
val t = new Tuple3(1, "hello",
Console)
To represent tuples, Scala
uses a series of classes: Tuple2, Tuple3, etc., through Tuple22. Each class has
as many type parameters as it has elements.
Accessing the elements
One way of accessing tuple
elements is by position. The individual elements are named _1, _2, and so
forth.
println(ingredient._1) //
Sugar
println(ingredient._2) //
25
Pattern matching on tuples
A tuple can also be taken
apart using pattern matching:
val (name, quantity) =
ingredient
println(name) // Sugar
println(quantity) // 25
Another example of pattern-matching a tuple:
val planets = List(("Mercury", 57.9),
("Venus", 108.2), ("Earth", 149.6),("Mars",
227.9), ("Jupiter", 778.3))
planets.foreach{
case
("Earth", distance) =>
println(s"Our planet is $distance million kilometers from the
sun")
case _ =>
}
Iterate over the Tuple
We use Tuple.productIterator() method to
iterate over all the elements of a Tuple.
Example
val t = (4,3,2,1)
t.productIterator.foreach{ i
=>println("Value = " + i )}
//Output
Value = 4
Value = 3
Value = 2
Value = 1
Creating a tuple with ->
Another cool feature, you can create a
tuple using this syntax:
1 -> "a"
This creates a Tuple2(1,a)
Tuples swap method
Example:
val t = Tuple2("Scala",
"hello")
println("Swapped Tuple: " +
t.swap )
//Output
Swapped Tuple: (hello,Scala)
t: (String, String) = (Scala,hello)
Note: swap operation performed on only
those tuples whose element count is 2 only. If element count is more than 2 it
will give you error
Example:
val t = Tuple3("Scala",
"hello","Sarvana")
println("Swapped Tuple: " +
t.swap )
//Output
error: value swap is not a member of
(String, String, String)
println("Swapped Tuple: " +
t.swap )
Converting Tuple to String in Scala
We can use tuple.toString() method to
concatenate elements of tuple to string.
val t = (1, "hello",20.2356)
val strVal = t.toString()
println("Concatenated String:
" + strVal)
//Output
Concatenated String: (1,hello,20.2356)
t: (Int, String, Double) =
(1,hello,20.2356)
strVal: String = (1,hello,20.2356)
No comments:
Post a Comment