Command line argumentsIntroduction to ScalaArraysTuples

Tuples

Like Python, Scala supports tuples:

scala> var a = (3, 5.0)
a: (Int, Double) = (3,5.0)
Unlike in Python, the parentheses are stricly necessary. Note the type: the first element of tuple a is an Int, the second one a Double. You can assign only tuples of the correct type to the variable a:
scala> a = (2, 7)
a: (Int, Double) = (2,7.0)
scala> a = (2.0, 7)
<console>:5: error: type mismatch;
 found   : Double(2.0)
 required: Int
 

You can access the elements of a tuple as fields _1, _2, and so on:

scala> a._1
res1: Int = 3

You can also "unpack" a tuple like in Python:

scala> val (x,y) = a
x: Int = 3
y: Double = 5.0
The parentheses around x and y are required—if you omit them, something completely different happens (try it)!

Like in Python, tuples are often used if you want to return more than one value from a function:

 scala> def unpackYYMM(n: Int): (Int, Int) = {
     |   (n / 100, n % 100)
     | }
unpackYYMM: (n: Int)(Int, Int)

scala> unpackYYMM(201202)
res4: (Int, Int) = (2012,2)

You can assign the results directly to separate variables:

scala> val (y, m) = unpackYYMM(201202)
y: Int = 2012
m: Int = 2
Command line argumentsIntroduction to ScalaArraysTuples