How is "Any" upper bound in Kotlin different from the default (no bounds)?

Viewed 303

This code fails to compile, with an error on the KClass type:

interface Foo<T> {
    val tClass: KClass<T>
}

Type argument is not within its bounds. Expected: Any, Found: T

This is saying that KClass needs an Any type parameter, but T is not an Any.

So what is the difference between these?

  • <T>
  • <T: Any>
  • <T: Any?>
2 Answers

To explain this it is best to start with the differences between the type system of Java versus Kotlin.

In Java all classes inherit from Object and Object can be both null or not. In Kotlin there is a distinction between nullable and non-nullable types. By default the base type is Any?

Therefore <T> is by default of type Any?. Since you are passing in a type that is non-nullable you need to declare that <T: Any> instead of Any?.

Therefore <T> is the same as <T: Any?> and <T: Any> says that only a type can be passed to this method that is non-nullable.

Related