Scala:为什么我可以将Int转换为Unit? [英] Scala: Why can I convert Int to Unit?
问题描述
我最近开始使用Scala(2.8),并注意到我可以编写以下代码(在Scala解释器中):
I've recently started playing with Scala (2.8) and noticed the I can write the following code (in the Scala Interpreter):
scala> var x : Unit = 10
x : Unit = ()
目前尚不清楚发生了什么.我真的没想到会看到任何对 Unit 的隐式转换.
It's not obvious what's going on there. I really didn't expect to see any implicit conversion to Unit.
推荐答案
请参见
See section "6.26.1 Value Conversions" in the Scala Language Specification version 2.8:
...
丢弃值.如果e
具有某种值类型,并且预期的类型为Unit,则将转换e
通过将其嵌入术语{ e; () }
中,将其更改为预期的类型.
Value Discarding. If e
has some value type and the expected type is Unit, e
is converted
to the expected type by embedding it in the term { e; () }
.
...
这篇关于Scala:为什么我可以将Int转换为Unit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!