Why var foo = null compiles

I start with Kotlin and try to understand something.

var foo: String = null not compiling as expected.

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

So why var foo = nullcompile?

+4
source share
3 answers

The type fooin this case will be inferred to Nothing?, which is a special type. In short, it Nothingis a type that is a subtype of each type in Kotlin (therefore Nothing?a subtype of each type NULL), has no instances, and can be used as a return type for functions that can never return.

Nothing , null Nothing?, .

Nothing , , .

+8

var foo = null Nothing?, .

+5

var foo = null var foo:Nothing? = null

var foo = "" var foo:String = ""

slo

var foo = 1 var foo:Int = 1

, foo .

+4

Source: https://habr.com/ru/post/1678288/


All Articles