Cyan Cyan - 3 years ago 231
Scala Question

Adding elements to a list in a for loop

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))

The code above is supposed to concatenate some lists. But the result is an empty list. Why?

Tom Tom
Answer Source

Your mistake is on the line locations ::: List(Location(x, y)). This is concatenating the lists, but the doing nothing with the result. If you replace it with locations = locations ::: List(Location(x, y)) you would have your desired result.

However there are more idiomatic ways to solve this problem in Scala. In Scala, writing immutable code is the preferred style (i.e. use val rather than var where possible).

Here's a couple of ways to do it:

Using yield:

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

Using tabulate:

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

Even shorter:

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

Edit: just noticed you had 0 to 10 which is inclusive-inclusive. 0 until 10 is inclusive-exclusive. I've changed the args to tabulate to 11.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download