在Nothing上调用任何方法 [英] Calling any method on Nothing

查看:163
本文介绍了在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()
}

这是错误还是功能?

注意:

  1. 第一段代码会编译(带有警告),第二段代码不会编译
  2. 可以使用Nothing类型的接收器,例如调用toString()
  3. 这是合法的:{b:Boolean -> b.not()}(q)
  4. 也要上流:(q as Boolean).not()
  5. Scala的等效问题
  1. First piece of code compiles (with warnings), second does not
  2. It's possible to use a Nothing typed receiver, for instance calling toString()
  3. This is legal: {b:Boolean -> b.not()}(q)
  4. Upcast too: (q as Boolean).not()
  5. Equivalent question for Scala

推荐答案

NothingNothing是有原因的.您不能在其上调用任何功能.除了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆