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?
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
As @jwvh mentioned List
s are immutable, so you should include full formula to calculate your list instead of element by element calculation
import scala.util.Random
val quantity = List(1,2,4,8,16)
val myList = for {
q ← quantity
} yield List.fill(q)(Random.nextInt(20000))
If you really like the imperative approach, you can use mutable builders to create your collection
import scala.collection.mutable.ListBuffer
import scala.util.Random
val quantity = List(1,2,4,8,16,32)
val myListBuffer = ListBuffer.empty[List[Int]]
for (i ← 0 until 6 )
myListBuffer += List.fill(quantity(i))(Random.nextInt(20000))
val myList = myListBuffer.toList
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.