2011-02-27 107 views
4

雖然我知道有更多的這樣做的idomatic方式,爲什麼不這個代碼工作? (主要是,爲什麼第一次嘗試只是x += 2工作。)這些看起來很奇特(至少對Scala來說是個新手)錯誤消息一些implicit def魔法不能正常工作?爲什麼+ =不適用於列表?

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) 

回答

10

您正在使用錯誤的操作符。

要附加到集合,您應該使用:+而不是+。這是因爲試圖通過使用+來鏡像Java的行爲而導致的與串連接的問題。

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

scala> x :+= 2 

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

如果要預先考慮,也可以使用+:

2

查看Scala API中的List。將元素添加到列表的方法是:

2 +: x 

x :+ 2 

2 :: x 
相關問題