开发者

Why += doesn't work with Lists?

开发者 https://www.devze.com 2023-02-13 14:03 出处:网络
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 newc

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 wor开发者_StackOverflow中文版king 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.

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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号