在 Nothing 上调用任何方法

2024-07-03

虽然它没有明确说明 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-nothing.htmlNothing 是所有类型的子类型,这(除其他外)表明:

fun f(x:Float) { }
fun g(x:Char) { }

fun dead(q: Nothing) {
    f(q)
    g(q)
}

然而,这会因“未解析的引用”而失败:

fun dead(q: Nothing) {
    q.not()
}

这是一个错误还是一个功能?

Notes:

  1. 第一段代码可以编译(有警告),第二段则不能
  2. 可以使用Nothing类型化接收者,例如调用toString()
  3. 这是合法的:{b:Boolean -> b.not()}(q)
  4. 也向上看:(q as Boolean).not()
  5. 同等问题 https://stackoverflow.com/questions/51042663/when-is-nothing-a-legal-receiver对于斯卡拉

Nothing is 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>()
}

Here Nothing表示没有子节点的叶节点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Nothing 上调用任何方法 的相关文章

随机推荐