3

我想澄清一些关于Unit和的细节Nothing

例如:

def unit(companyId: Int): Unit = {}

def Nothing(companyId: Int): scala.Nothing = {}

根据文档, in Scala 与inUnit非常相似。但voidJava

test("test Unit and Nothing") {
  println(unit(1))
}
  • Unit返回 -()

  • Nothing不返回任何东西。

为什么 Scala 有返回的溢出类型?为什么 Scala 不能使用代替?UnitNothingNothingUnit

4

1 回答 1

12

Unit基数为 1。Nothing基数为 0。

你的第二个例子

def Nothing(companyId: Int): scala.Nothing = {}

不编译。不可能返回 a Nothing,因为Nothing没有居民。因此返回的函数Nothing不能正常返回;它只能抛出异常。

def Nothing(companyId: Int): scala.Nothing = { throw new Exception(); }

Java 的Void可比性Unit在于Void也具有基数 1;它唯一的居民是null。Java 中没有基数为 0 的类型(也不可能定义这样的类型),因此 Java 没有可与Nothing. 当然,可以编写一个总是抛出异常的 Java 方法,但返回类型不可能表达这一点。


考虑在集合中使用这些中的每一个时会发生什么。例如, aList[Unit]可以包含任意数量的Unit值:

List()           : List[Unit]
List((), (), ()) : List[Unit]

而 aList[Nothing]必然是空的,因为你不能把任何东西放进去。

List()           : List[Nothing]

另一个需要注意的重要事情Nothing是它是所有其他类型的子类型。这是有道理的,因为它没有居民;因此,关于实例的每个命题(命题与类型密切相关Nothing)都是空洞的。关于为什么这很有用的一个例子,再次考虑列表:

List.empty[Nothing] : List[String]

这里我们将 a 赋予List[Nothing]类型List[String],我们可以这样做,因为List的类型参数是协变的并且Nothing是 的子类型String。请注意,我们不能用 a 来做到这一点List[Unit],因为Unit不是的子类型String

于 2016-03-07T22:02:34.847 回答