Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why += doesn't work with Lists?

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)
like image 904
Aaron Yodaiken Avatar asked Dec 17 '22 16:12

Aaron Yodaiken


1 Answers

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.

scala> var x: List[Int] = List(1)
x: List[Int] = List(1)

scala> x :+= 2

scala> x
res1: List[Int] = List(1, 2)

You can also use +: if you want to prepend.

like image 146
Kevin Wright Avatar answered Dec 29 '22 00:12

Kevin Wright