为什么var foo = null编译 [英] Why does var foo = null compile
问题描述
我从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编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!