Reputation: 23
I have made a list to store some sequences of data, where each sequence contains three elements. How can I extract one of the elements from the sequence?
I have tried parentheses, like alco(0)(1) and get() and they do not work.
val alco = List(("Light Beer", "4%", "23 OZ"), ("Regular Beer", "6%", "23 OZ"))
val temp = alco(0).get(1)
println(temp)
The result shows:
error: value get is not a member of (String, String, String) val temp = alco(0).get(1)
Upvotes: 2
Views: 70
Reputation: 3181
As @Andriy pointed out:
val alco = List(("Light Beer", "4%", "23 OZ"), ("Regular Beer", "6%", "23 OZ"))
is of type List[Tuple3[String, String, String]]
and since Tuple3
does not have a get
method you're receiving the error.
To solve the problem just define your list as follows:
val alco = List(List("Light Beer", "4%", "23 OZ"), List("Regular Beer", "6%", "23 OZ"))
This way it will be of type List[List[String]]
and your code should work.
Upvotes: 1
Reputation: 7989
scala> val alco = List(("Light Beer", "4%", "23 OZ"), ("Regular Beer", "6%", "23 OZ"))
alco: List[(String, String, String)] = List((Light Beer,4%,23 OZ), (Regular Beer,6%,23 OZ))
scala> val (_, temp, _) = alco(0)
temp: String = 4%
scala> val temp = alco(0)._2
temp: String = 4%
Beware that accessing to the Scala list by index has O(n)
complexity where n
is size of the list. So if you want to iterate over them - prefer to use map
, collect
, foldLeft
or foreach
calls:
scala> alco.map { case (_, temp, _) => temp }
res0: List[String] = List(4%, 6%)
scala> alco.foreach { x => println(x._2) }
4%
6%
Upvotes: 3