Why does var foo = null compile

2019-02-24 00:40发布

问题:

I am starting with Kotlin and trying to understand something.

var foo: String = null does not compile as expected.

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

So why does var foo = null compile??

回答1:

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.

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

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.



回答2:

For var foo = null, the type is inferred to Nothing?, and is therefore valid syntax.



回答3:

var foo = null is equivalent to var foo:Nothing? = null

similarly

var foo = "" is equivalent to var foo:String = ""

and slo

var foo = 1 is equivalent to var foo:Int = 1

The compiler is smart enough to infer the type of foo from the right hand expression type.



标签: kotlin