"+=" will reassign or not?
See the following code:
val names = Set("Mike", "Jack")
names += "Jeff"
There will be an error:
error: reassignment to val
I see i开发者_StackOverflow社区n 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 +=)
class Test(num: Int) {
def +(n: Int) = new Test(num + n);
override def toString = num.toString
}
defined class Test
val foo = new Test(5)
foo: Test = 5
foo += 4
error: reassignment to val
foo += 4
^
var bar = new Test(5)
bar: Test = 5
bar += 4
bar
res12: Test = 9
A short answer:
scala> val names = collection.mutable.Set("Mike", "Jack")
names: scala.collection.mutable.Set[java.lang.String] = Set(Jack, Mike)
scala> names += "Jeff"
res23: names.type = Set(Jack, Jeff, Mike)
or you can import the mutable Set like this:
import scala.collection.mutable.Set
精彩评论