我从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编译
发布评论