如何重载 null 运算符?

发布于 2025-01-13 19:04:34 字数 136 浏览 3 评论 0原文

我想重载一个运算符,例如 invoke for null 文字。

例如,我可以写类似这样的内容:

null(1, 2)

可能吗?

I would like to overload an operator like invoke for null literal.

For example, so I could writen something like

null(1, 2)

Is it possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁的新欢旧爱 2025-01-20 19:04:34

我不建议在 null 文字上重载任何内容,因为它会导致太多混乱并且没有实际用例。

不过,从技术上讲,这是可能的:

operator fun Nothing?.invoke() = "hi!"

fun main() {
    println(null())  // Works, prints "hi!"

    val x = null
    println(x())  // Also works.

    val y: String? = null
    //println(y())  // compilation error

    val z: String = ""
    //println(z())  // also compilation error
}

它利用了 null 关键字具有可为空类型 Nothing? 的事实。

I wouldn't advise overloading anything on the null literal, as it would cause too much confusion and would have no real-world use case.

However, technically, it's possible:

operator fun Nothing?.invoke() = "hi!"

fun main() {
    println(null())  // Works, prints "hi!"

    val x = null
    println(x())  // Also works.

    val y: String? = null
    //println(y())  // compilation error

    val z: String = ""
    //println(z())  // also compilation error
}

It makes use of the fact that the null keyword has the nullable type Nothing?.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文