4

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

Distwo
  • 11,569
  • 8
  • 42
  • 65

3 Answers3

9

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.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • why it infers to Nothing? instead of Any? ? – Anastasiia Chervinska Sep 13 '18 at 18:38
  • The compiler always infers the most concrete type it can - `Nothing?` is the most concrete type here, and `Any?` would be the least concrete (so the broadest) type overall. Imagine how annoying it would be if every variable was always inferred to be an `Any?`. – zsmb13 Sep 13 '18 at 19:13
  • but in case var foo = 1, Nothing will be the most concrete type, however it will infer to Int, right? – Anastasiia Chervinska Sep 14 '18 at 17:18
5

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

nhaarman
  • 98,571
  • 55
  • 246
  • 278
4

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.

miensol
  • 39,733
  • 7
  • 116
  • 112