We've been using Kotlin for a good while, but it j...
# announcements
b
We've been using Kotlin for a good while, but it just now occurred to me to wonder about this bit of type-inference trivia: An unconstrained generic parameter
T
is basically equivalent to
<T : Any?>
. Why then is a value
value: T
not smart-cast to
T2
such that
<T2 : Any>
? The motivating example that I wanted (and which failed) was something like:
Copy code
fun <T> assertIsInstanceOf(value: T, type: KClass<*>) {
  if (value != null) {
    assert(type.java.isAssignableFrom(value.javaClass)) // this fails to compile as 'javaClass' does not exist on `Any?`
  }
}
The workaround was to declare the function
fun <T : Any> assertIsInstanceOf(value: T?, type: KClass<*>)
, which seems to work, but feels unsatisfying. What could I be missing about generics and smart-casting?