Scala nested Lists

Viewed 1790

I’m trying to fetch a value from a nested list in Scala but somehow I’m not able to find a solution.

I’ve created a list as:

var list3 = List((1,2,3),(4,5,6),(7,8),(9,10,11,12))

I require 7 as the output.

In Python, for the same thing, I’m creating list as

list3 = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]

To get the output as 7, I’m using

list3[len(list3) -2][len(list3) -4]

Please suggest me how to achieve the same in Scala.

Thanks in advance.

2 Answers

list3 isn't a list-of-lists, it's a list of tuples. You can create a list-of-lists as follows:

var list3 = List(List(1,2,3),List(4,5,6),List(7,8),List(9,10,11,12))

Then, the Scala version of your python code would work:

scala> list3(list3.size - 2)(list3.size - 4)
res3: Int = 7

You can use productElement as below

scala> var list3 = List((1,2,3),(4,5,6),(7,8),(9,10,11,12))
list3: List[Product with Serializable] = List((1,2,3), (4,5,6), (7,8), (9,10,11,12))

scala> list3(list3.length -2).productElement(list3.length-4)
res0: Any = 7
Related