2

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
  • 2
    a = a ++ a should be sufficient. Avoid mutables whenever possible. (It is almost always possible.) Commented Jun 13, 2020 at 7:02

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.