[Solved] Scala – why does :: not change a List? [duplicate]


Because x :: xs returns a new list, where the first element is x, followed by xs.

So, to make your code work, make list a var and re-assign it inside the loop:

var list = List[Int]()

while(list.length < 20)
  list = Random.nextInt(100) :: list

However, the idiomatic way of doing this in Scala is to not use mutations at all (local mutable state is fine sometimes though). “While” loops can usually be replaced with a recursive function:

def go(xs: List[Int]) =
  if (xs.length >= 20) xs
  else go(Random.nextInt(100) :: xs)

go(List())

This particular scenario can also be solved using List.fill instead

val list = List.fill(20)(Random.nextInt(100))

2

solved Scala – why does :: not change a List? [duplicate]