我想澄清一些有关\\<REMOTE MACHINE'S IP>\
和Unit
的详细信息。
例如:
Nothing
根据文档,Scala中的def unit(companyId: Int): Unit = {}
def Nothing(companyId: Int): scala.Nothing = {}
与Unit
中的void
非常相似。但
Java
test("test Unit and Nothing") {
println(unit(1))
}
返回 - Unit
()
不会返回任何内容。
为什么Scala的 溢出 类型Nothing
会返回Unit
?
为什么Scala无法使用Nothing
代替Nothing
?
答案 0 :(得分:9)
Nothing
有基数1. def Nothing(companyId: Int): scala.Nothing = {}
基数为0.
你的第二个例子
Nothing
没有编译。归因Nothing
是不可能的,因为Nothing
没有居民。因此,返回def Nothing(companyId: Int): scala.Nothing = { throw new Exception(); }
的函数无法正常返回;它只能抛出异常。
Void
Java Unit
与Void
相当,null
也有基数1;唯一的居民是Nothing
。 Java中没有基数为0的类型(也不可能定义这样的类型),因此Java没有与List[Unit]
相当的类型。
当然,编写一个始终抛出异常的Java方法是可能的,但返回类型不可能表达异常。
考虑在集合中使用每个集合时会发生什么。例如,Unit
可以包含任意数量的List() : List[Unit]
List((), (), ()) : List[Unit]
值:
List[Nothing]
而List() : List[Nothing]
必然是空的,因为你无法投入其中。
Nothing
关于Nothing
的另一个重要注意事项是,它是所有其他类型的子类型。这是有道理的,因为它没有居民;因此关于List.empty[Nothing] : List[String]
个实例的每个命题(propositions are closely related to types)都是空洞的。有关其有用的示例,请再次考虑列表:
List[Nothing]
我们将List[String]
归因于类型List
,我们可以这样做,因为Nothing
的类型参数是协变的,String
是子类型List[Unit]
。请注意,我们无法使用Unit
执行此操作,因为String
不是 {{1}}的子类型。