为什么var foo = null编译

编程入门 行业动态 更新时间:2024-10-26 11:29:28
本文介绍了为什么var foo = null编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我从Kotlin开始,试图理解一些东西.

I am starting with Kotlin and trying to understand something.

var foo: String = null无法按预期编译.

var foo: String? = null应该是正确的语法,并且可以按预期进行编译.

var foo: String? = null should be the correct syntax and compile as expected.

那为什么var foo = null可以编译?

推荐答案

在这种情况下,foo的类型将被推断为Nothing?,这是一种非常特殊的类型.简而言之,Nothing是Kotlin中每种类型的子类型的类型(因此Nothing?是每种可空类型的子类型),没有实例,并且可以用作永不返回的函数的返回类型

The type of foo in this case will be inferred to Nothing?, which is a very special type. In short, Nothing is a type that is a subtype of every type in Kotlin (therefore Nothing? is a subtype of every nullable type), has no instances, and can be used as a return type for functions that can never return.

即使Nothing不能有实例,null本身的类型为Nothing?,这就是为什么可以将其分配给任何可为空的变量的原因.

Even though Nothing can have no instances, null itself of type Nothing?, which is why it can be assigned to any nullable variable.

您可以在官方网站上深入了解Nothing docs ,在这篇出色的中型文章中,并在本文中介绍了整个Kotlin类型层次结构.

You can learn more in depth about Nothing in the official docs, in this excellent Medium article, and in this article that covers the overall Kotlin type hierarchy.

更多推荐

为什么var foo = null编译

本文发布于:2023-10-16 15:57:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498042.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:var   foo   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!