Nothing
是Nothing
有原因的。你不能在上面调用任何函数。此外not()
仅适用于,Boolean
因此它不存在于 上Nothing
。实际上没有方法Nothing
:
/**
* Nothing has no instances. You can use Nothing to represent "a value that never exists": for example,
* if a function has the return type of Nothing, it means that it never returns (always throws an exception).
*/
public class Nothing private constructor()
该文档几乎解释了它的存在。
不过有一个漏洞。如果Nothing?
从函数返回会发生什么?
fun dead(): Nothing? {
return null
}
这是正确的。它只能返回null
:
@JvmStatic
fun main(args: Array<String>) {
dead() // will be null
}
我不会说有一个有效的用例可以做到这一点,但这是可能的。
Nothing
在树中表示虚无的示例:
sealed class Tree<out T>() {
data class Node<out T>(val value: T,
val left: Tree<T> = None,
val right: Tree<T> = None): Tree<T>()
object None: Tree<Nothing>()
}
这里Nothing
表示没有子节点的叶节点。