在Nothing上调用任何方法 [英] Calling any method on Nothing
问题描述
尽管没有明确说明是所有类型的子类型,这(除其他外)建议:
Although it is not explicitly stated that Nothing is the subtype of all types, this (among others) suggests it:
fun f(x:Float) { }
fun g(x:Char) { }
fun dead(q: Nothing) {
f(q)
g(q)
}
但是,此操作失败,并显示未解析的引用":
However, this fails with "unresolved reference":
fun dead(q: Nothing) {
q.not()
}
这是错误还是功能?
注意:
- 第一段代码会编译(带有警告),第二段代码不会编译
- 可以使用
Nothing
类型的接收器,例如调用toString()
- 这是合法的:
{b:Boolean -> b.not()}(q)
- 也要上流:
(q as Boolean).not()
- Scala的等效问题
- First piece of code compiles (with warnings), second does not
- It's possible to use a
Nothing
typed receiver, for instance callingtoString()
- This is legal:
{b:Boolean -> b.not()}(q)
- Upcast too:
(q as Boolean).not()
- Equivalent question for Scala
推荐答案
Nothing
为Nothing
是有原因的.您不能在其上调用任何功能.除了not()
仅适用于Boolean
,因此它不在Nothing
上.实际上,Nothing
上没有任何方法:
Nothing
is Nothing
for a reason. You can't call any functions on it. Besides not()
is only applicable for Boolean
so it is not present on Nothing
. In fact there are no methods on 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()
文档几乎解释了它的存在.
The documentation pretty much explains its existence.
尽管有一个漏洞.如果从函数返回Nothing?
会怎样?
There is one loophole though. What happens if you return Nothing?
from a function?
fun dead(): Nothing? {
return null
}
是的.它只能返回null
:
@JvmStatic
fun main(args: Array<String>) {
dead() // will be null
}
我不会说有一个有效的用例可以做到这一点,但是有可能.
I wouldn't say that there is a valid use case to do this but it is possible.
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
表示没有子节点的叶节点.
Here Nothing
denotes a leaf node with no children.
这篇关于在Nothing上调用任何方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!