Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does var foo = null compile

Tags:

kotlin

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??

like image 838
Distwo Avatar asked Dec 01 '22 11:12

Distwo


1 Answers

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.

like image 73
zsmb13 Avatar answered Dec 04 '22 14:12

zsmb13