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??
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With