为什么 += 不适用于列表?
尽管我知道有更多的惯用方法可以做到这一点,但为什么这段代码不起作用? (大多数情况下,为什么第一次尝试只是 x += 2
不起作用。)这些看起来很奇怪的错误消息(至少对于 Scala 的新手来说是这样)是否是一些隐式定义 魔法不起作用吧?
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)
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 working 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用了错误的运营商。
要附加到集合,您应该使用
:+
而不是+
。这是因为尝试使用+
连接字符串来反映 Java 的行为时会出现问题。如果您想添加前缀,也可以使用
+:
。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.You can also use
+:
if you want to prepend.查看 Scala 中的 List API。将元素添加到列表的方法有:
Have a look at the List in the Scala API. Methods for adding an element to a list are: