Aaron Yodaiken
Aaron Yodaiken

Reputation: 19551

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)

Upvotes: 4

Views: 1140

Answers (2)

Thomas Rawyler
Thomas Rawyler

Reputation: 1095

Have a look at the List in the Scala API. Methods for adding an element to a list are:

2 +: x

x :+ 2

2 :: x

Upvotes: 2

Kevin Wright
Kevin Wright

Reputation: 49705

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.

Upvotes: 10

Related Questions