Why does + = not work with lists?

Although I know there are more idomatic ways to do this, why does this code not work? (Basically, why does the first attempt fail only with x += 2 ) Are these rather peculiar views (for Scala newbies) of error messages that some magic of implicit def not working correctly?

 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) 
+4
source share
2 answers

You are using the wrong operator.

To add to the collection, you should use :+ , not + . This is due to problems encountered when trying to reflect Java behavior using + to concatenate 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 add.

+10
source

See List in the Scala API. Methods for adding an item to the list:

 2 +: x x :+ 2 2 :: x 
+2
source

Source: https://habr.com/ru/post/1341538/


All Articles