1

Here's the problem:

I intend to retrieve a (Int, Int) object from a function, but I don't know how to get the second element. I've tried the following commands so as to retrieve the second value, or convert it to a Seq or List, but with no luck.

scala> val s = (1,2)
s: (Int, Int) = (1,2)

scala> s(1)
<console>:9: error: (Int, Int) does not take parameters
              s(1)
               ^

scala> val ss = List(s)
ss: List[(Int, Int)] = List((1,2))

scala> ss(0)
res10: (Int, Int) = (1,2)

Could anyone give me some idea? Thanks a lot!

Judking
  • 6,111
  • 11
  • 55
  • 84
  • 1
    http://stackoverflow.com/questions/6884298/why-is-scalas-syntax-for-tuples-so-unusual – senia Feb 03 '15 at 13:23

1 Answers1

5
val s = (1, 2)

is syntatic sugar and creates a Tuple2, or in other words is equivalent to new Tuple2(1, 2). You can access elements in tuples with

s._1 // => 1
s._2 // => 2

Likewise, (1, 2, 3) would create a Tuple3, which also has a method _3 to access the third element.

Leo
  • 37,640
  • 8
  • 75
  • 100
  • Thanks bro, this is what I need. Actually, if you didn't give me this hint, not even do I know what keyword to google about... :] – Judking Feb 03 '15 at 13:23
  • 2
    It might be useful to add that another way to extract the content of the tuple is with pattern matching, for instance: `val (a, b) = (1, 2)` will affect a=1, b=2. – Cyäegha Feb 03 '15 at 17:23