I2obiN I2obiN - 1 year ago 120
Scala Question

Instantiating a List of a List in Scala

I have a list of a list of integers in Scala, while the interpreter/compiler doesn't throw any warnings, when I go to run the worksheet I get an error "not found: value table"

var mylist: List[List[Int]]

for (i <- 1 to 10) {
mylist = List(List(i, Random.nextInt(20000), quantity(i)))

As far as I know, i is an Int, nextInt will return an Int, and quantity is a predetermined list of Ints.

I'm guessing I need to instantiate the table variable, how should I go about that?

Answer Source

There's a difference between a var that holds an immutable collection, and a val that holds a mutable collection. The former (var) can hold a different collection at some later time. The latter (val) can only hold the one given collection, but the contents of that collection can change over time.

Even though mylist is a var, a List[List[Int]] is immutable. You can't modify its contents.

To create the collection you want you might try something like this.

val mylist = (1 to 10).map(x => List(x, Random.nextInt(2000), quantity(x))).toList