将元素添加到for循环中的列表

时间:2017-11-23 22:07:47

标签: scala scala-collections

var locations: List[Location] = List[Location]()
for (x <- 0 to 10; y <- 0 to 10) {
    println("x: " + x + " y: " + y)
    locations ::: List(Location(x, y))
    println(locations)
}

上面的代码应该连接一些列表。但结果是一个空列表。为什么呢?

1 个答案:

答案 0 :(得分:3)

你的错误在locations ::: List(Location(x, y))行。这是连接列表,但结果无效。如果将其替换为locations = locations ::: List(Location(x, y)),您将获得所需的结果。

然而,在Scala中有更多惯用的方法可以解决这个问题。在Scala中,编写不可变代码是首选样式(即尽可能使用val而不是var

以下是几种方法:

使用yield:

val location = for (x <- 0 to 10; y <- 0 to 10) yield Location(x, y)

使用制表:

val location = List.tabulate(11, 11) { case (x, y) => Location(x, y) }

更短:

val location = List.tabulate(11, 11)(Location)

修改:刚刚发现你有0 to 10这是包容性的。 0 until 10是包容性的。我已经将args更改为11表格。

相关问题