I'm new to scala, and what I'm learning is tuple
.
I can define a tuple as following, and get the items:
val tuple = ("Mike", 40, "New York") println("Name: " + tuple._1) println("Age: " + tuple._2) println("City: " + tuple._3)
My question is:
Thanks in advance!
In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.
Tuple are of type Tuple1 , Tuple2 ,Tuple3 and so on. There is an upper limit of 22 for the element in the tuple in the scala, if you need more elements, then you can use a collection, not a tuple.
Scala tuple combines a fixed number of items together so that they can be passed around as a whole. Unlike an array or list, a tuple can hold objects with different types but they are also immutable. The following is an example of a tuple holding an integer, a string, and the console.
One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.
1] tuple.productArity
2] No.
3] Some interesting operations you can perform on tuples: (a short REPL session)
scala> val x = (3, "hello") x: (Int, java.lang.String) = (3,hello) scala> x.swap res0: (java.lang.String, Int) = (hello,3) scala> x.toString res1: java.lang.String = (3,hello) scala> val y = (3, "hello") y: (Int, java.lang.String) = (3,hello) scala> x == y res2: Boolean = true scala> x.productPrefix res3: java.lang.String = Tuple2 scala> val xi = x.productIterator xi: Iterator[Any] = non-empty iterator scala> while(xi.hasNext) println(xi.next) 3 hello
See scaladocs of Tuple2, Tuple3 etc for more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With