Scala:为什么我可以将Int转换为Unit?

PGe*_*ene 20 scala unit-type

我最近开始玩Scala(2.8)并注意到我可以编写以下代码(在Scala Interpreter中):

scala> var x : Unit = 10
x : Unit = ()
Run Code Online (Sandbox Code Playgroud)

现在发生的事情并不明显.我真的没想到看到任何隐含的单位转换.

mkn*_*ssl 33

请参阅Scala语言规范 2.8版中的"6.26.1值转换"部分:

...

价值丢弃.如果e具有某种值类型且预期类型为单位,e则通过将其嵌入到术语中将其转换为预期类型{ e; () }.

...


Dav*_*ith 15

任何东西都可以转换成单位.这对于支持仍然返回值的副作用方法来说是必要的,但是返回值经常被忽略.例如

import java.util.{List =>JList}

def remove2[A](foo: JList[A], a1:A, a2:A):Unit = {
    foo.remove(a1)
    foo.remove(a2)  //if you couldn't convert the (usually pointless) return value of remove to Unit, this wouldn't type
}
Run Code Online (Sandbox Code Playgroud)