Although I know that there are more idomatic ways of doing this, why doesn’t this code work? (Mostly, why doesn’t the first attempt at just x += 2 work.) Are these quite peculiar looking (for a newcomer to Scala at least) error messages some implicit def magic not working right?
scala> var x: List[Int] = List(1)
x: List[Int] = List(1)
scala> x += 2
<console>:7: error: type mismatch;
found : Int(2)
required: String
x += 2
^
scala> x += "2"
<console>:7: error: type mismatch;
found : java.lang.String
required: List[Int]
x += "2"
^
scala> x += List(2)
<console>:7: error: type mismatch;
found : List[Int]
required: String
x += List(2)
You’re using the wrong operator.
To append to a collection you should use
:+and not+. This is because of problems caused when trying to mirror Java’s behaviour with the use of+for concatenating to Strings.You can also use
+:if you want to prepend.