我有一个变量v
,Vector
我正在尝试使用它添加一个元素+=
.它抱怨它期望String
而不是Int
:
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45). Type in expressions to have them evaluated. Type :help for more information. scala> var v = Vector[Int]() v: scala.collection.immutable.Vector[Int] = Vector() scala> v += 3:9: error: type mismatch; found : Int(3) required: String v += 3 ^
它为什么期待String
?当我给它一个String
(当然是错误的),它说它期望Vector[Int]
:
scala> v += "three":9: error: type mismatch; found : String required: scala.collection.immutable.Vector[Int] v += "three" ^
当我给它一个时Vector[Int]
,它再次期望String
:
scala> v += Vector(3):9: error: type mismatch; found : scala.collection.immutable.Vector[Int] required: String v += Vector(3) ^
为什么会这样?
我知道我可以使用添加元素+:=
.但为什么我不能使用+=
,比如一个Set
?
让我们逐个审视这个案例:
scala> v += 3 <console>:9: error: type mismatch; found : Int(3) required: String v += 3 ^
这是Vector没有+
方法的主要问题,因此编译器将默认为字符串连接(顺便提一下,这最近被批评为设计缺陷).问题是左侧(矢量)可以自动转换为字符串(通过Vector.toString),但右侧不是.
scala> v += "three" <console>:9: error: type mismatch; found : String required: scala.collection.immutable.Vector[Int] v += "three" ^
这里串联是可以的,但是你试图将String类型的结果放到Vector [Int]类型的变量中,这就是编译器抱怨的原因.但是如果你将v定义为任何编译器将停止抱怨:
var v: Any = Vector[Int]() v += "foo" // res1: Any = Vector()foo
现在,下一个案例
scala> v += Vector(3) <console>:9: error: type mismatch; found : scala.collection.immutable.Vector[Int] required: String v += Vector(3) ^
再次进行字符串连接,同样,String类型的结果将转到Vector类型的变量.
现在,谈论为什么Vector没有相同的+操作:普通的Set没有顺序的概念,而Vector和Seq一般都有和+会让人困惑:我是添加到结尾还是开始?因此,您必须明确决定是否使用:+或+:而不是隐式规则.