在 Scala 中实例化列表的列表

Instantiating a List of a List in Scala

我在 Scala 中有一个整数列表,而 interpreter/compiler 没有发出任何警告,当我转到 运行 工作表时,我得到一个错误 "not found: value table"

var mylist: List[List[Int]]

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

据我所知,i是一个Int,nextInt将return一个Int,quantity是一个预先确定的Int列表。

我想我需要实例化 table 变量,我应该怎么做?

包含不可变 collection 的 var 和包含可变 collection 的 val 之间存在差异。前者 (var) 可以在以后的某个时间持有不同的 collection。后者 (val) 只能容纳给定的 collection,但 collection 的内容会随时间变化。

尽管 mylistvar,但 List[List[Int]] 是不可变的。您无法修改其内容。

要创建您想要的 collection,您可以尝试这样的方法。

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

正如@jwvh 提到的,List 是不可变的,因此您应该包括完整的公式来计算您的列表,而不是逐个元素计算

import scala.util.Random

val quantity = List(1,2,4,8,16)
val myList =  for {
  q ← quantity
} yield List.fill(q)(Random.nextInt(20000))

如果您真的喜欢命令式方法,您可以使用可变构建器来创建您的集合

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