I assume that you are a Java programmer, and that is why you have a problem in order to understand what the problem is. In Java, if you try to change the list, even in a method, you can do this because a new collection is not created; This is a collection with an added item.
However, in Scala, since the list itself is not changed, then a completely new list needs to be created, and therefore a reassignment of the variable pointing to the list is required. Since in Scala, the val values passed in the arguments, this reassignment causes a problem. A new list is created in your first code, but since list is var, this reassignment does not cause problems.
If the List itself was changed, then you would not have problems in the second block of code, since you did not need to reassign the list. To prove this point, use ListBuffer instead of List in the second block of code, and you will see that it works fine.
source share