Search code examples
genericsinheritancenullablekotlin

What is the place in type hierarchy of nullable types?


You can inherit type A from type B, but whenever you define type A you will get type A? (nullable on) for free. But where does it lie exactly in type hierarchy? A? inherits from A or other way around?

I ask this because I am puzzled with such code:

open class Foo {
  fun foo() : Int {
    return 0;
  }
}

fun test<T : Foo?>(x:T) : Int {
  return x.foo() // (@)
}

fun main(args: Array<String>) {
  println(test<Foo?>(null))
} 

I don't understand why line (@) is compiled? Or in other words I don't understand nullable types hierarchy then, because until now I though of T as Foo? or any type derived from it. Can you derive non-nullable type from nullable one and what it would mean then?

Sorry if this is something obvious, I am just learning Kotlin.

(@) for nullable types it should be x!!.foo().


Solution

  • This is a bug in the compiler. You should not be able to call a member of a T when T has a nullable upper bound. X? is a supertype of X.