Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple question about tuple of scala

Tags:

tuples

scala

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:

  1. How to get the length of a tuple?
  2. Is tuple mutable? Can I modify its items?
  3. Is there any other useful operation we can do on a tuple?

Thanks in advance!

like image 874
Freewind Avatar asked Jul 27 '10 13:07

Freewind


People also ask

What is the use of tuples in Scala?

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.

What is the maximum size of tuple in Scala?

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.

Can we have variables of different types inside of a tuple in Scala?

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.

What is the difference between list and tuple in Scala?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.


1 Answers

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.

like image 165
missingfaktor Avatar answered Sep 27 '22 20:09

missingfaktor