See the following code:
val names = Set("Mike", "Jack")
names += "Jeff"
There will be an error:
error: reassignment to val
I see in some books, it said += is actually a method, and the code can be:
val names = Set("Mike", "Jack")
names.+=("Jeff")
If += is a method, why will it assign the “names”?
scala.collection.mutable.Set has += method. So irrespective of val or var, you are just invoking a method on the underlying set. But scala.collection.immutable.Set has no += method but has + method. += has special meaning in Scala; It can be applied like this, names = names + “Jeff” and since this is reassignment to a val ‘names’, the compiler is reporting the error.
Example (+ is applied and reassignment is done in place of +=)