Marta Karas
Marta Karas

Reputation: 5155

How to retrieve an element of ("1", "2", "3") Scala object?

I am stuck in an embarrassingly simple issue in Scala (which I am new to).

How to retrieve second (let's say) element ("2") from such a structure in Scala:

scala> val a = ("1", "2", "3")
a: (String, String, String) = (1,2,3)

Upvotes: 0

Views: 160

Answers (3)

Chris Martin
Chris Martin

Reputation: 30736

You can use getClass to see that the class's name is scala.Tuple3.

scala> a.getClass.getName
res0: java.lang.String = scala.Tuple3

Unfortunately, the documentation for Tuple3 is hidden in the API, but you can get to it with this direct link.

http://www.scala-lang.org/api/current/#scala.Tuple3

A tuple of 3 elements; the canonical representation of a scala.Product3.

_1 - Element 1 of this Tuple3

_2 - Element 2 of this Tuple3

_3 - Element 3 of this Tuple3

Alternatively, you could have used tab completion in the REPL to see the list of public members of a.

scala> a.
_1                _2                _3
asInstanceOf      canEqual          copy
isInstanceOf      productArity      productElement
productElements   productIterator   productPrefix
toString          zip               zipped            

So, the answer is: You can access the _2 field directly.

scala> a._2
res1: java.lang.String = 2

Although this is generally discouraged in favor of pattern matching.

scala> a match { case (x, y, z) => y }
res2: java.lang.String = 2

Upvotes: 1

Electric Coffee
Electric Coffee

Reputation: 12104

When dealing with tuples you can do either of the following:

val res = a._2

val (_, res, _) = a // sets res to "2"

val res = a match { case (_, i, _) => i } // same as above, just longer

// if your tuple appears in a list you can do something like this:
lst.map{ case (_, i, _) => /* do stuff with i */ }

Upvotes: 5

eeq
eeq

Reputation: 1004

When dealing with tuples try just this expression: a._2

Upvotes: 3

Related Questions