Why ++= is not working with the same list in Scala?

Viewed 71

I understand that ++= is used for appending one List to another. However, when the appending List is itself it does not seem to work. when I run this code:

var a = ListBuffer[Int](1, 2, 3)
a ++= a
println(a)

the program seems to stuck in a infinite loop and never stop.

1 Answers

The reason for the app to be stuck is that you're adding the mutable list to itself. The addition ++= is iterating over right side and adding elements to the left side. But, as the right side equals to the left side, every addition is increasing right side and it never gets till the end. Causing the infinite loop.

This is the source of ListBuffer.addAll method that is causing the problem.

  def addAll(xs: IterableOnce[A]): this.type = {
    val it = xs.iterator
    while (it.hasNext) {
      addOne(it.next())
    }
    this
  }

You should use a = a ++ a that concatenates two collections into a new collection without modifying the original ones and assigning the result to variable a.

Scala does not support reassignment after applying operator <OPERATOR>= as Java does for example and it provides operators that emulate this behaviour but in reality they come with different implementations.

Thus, a ++= a is not entirely the same as a = a ++ a

Related