gpt4 book ai didi

scala - Vector 上的 += 会出现奇怪/错误的类型错误

转载 作者:行者123 更新时间:2023-12-04 19:07:29 26 4
gpt4 key购买 nike

我有一个变量 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
<console>:9: error: type mismatch;
found : Int(3)
required: String
v += 3
^

为什么它期望 String ?当我给它一个 String (这当然是错误的),它说它期望一个 Vector[Int] :
scala> v += "three"
<console>:9: error: type mismatch;
found : String
required: scala.collection.immutable.Vector[Int]
v += "three"
^

当我给它一个 Vector[Int] ,它再次期待 String :
scala> v += Vector(3)
<console>: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 没有 + 的主要问题。方法,所以编译器会 default to string concatination (顺便说一下,这最近被高度批评为设计缺陷)。问题是左侧(向量)可以自动转换为字符串(通过 Vector.toString),而右侧则不是。
scala> v += "three"
<console>:9: error: type mismatch;
found : String
required: scala.collection.immutable.Vector[Int]
v += "three"
^

这里连接没问题,但您试图将 String 类型的结果放入 Vector[Int] 类型的变量,这就是编译器提示的原因。但是如果你将 v 定义为 Any 编译器将停止提示:
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 通常有 and + 会令人困惑:我是添加到结尾还是开头?因此,您必须明确决定是使用 :+ 还是 +:,而不是隐式规则。

关于scala - Vector 上的 += 会出现奇怪/错误的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20800102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com