If class `Apple` extends class `Fruit`, how can I ...
# reflect
v
If class
Apple
extends class
Fruit
, how can I create a map like
mapOf<String,KClass<Fruit>>("apple" to Apple)
?
e
that would be a
Copy code
Map<String, KClass<out Fruit>>
as
KClass<T>
is invariant
v
Thank you. I knew I had done it somewhere before but it never really "sticks" with me.
Harder question: given a function
suspend inline fun <reified T : Fruit> eat()
, how do I call something like
Copy code
val food = mapOf<String, KClass<Fruit>>("apple" to Apple)
val apple = food["apple"]
eat<apple> // this bit I struggle!
e
that's not possible - the type cannot be statically determined at compile time, which is necessary for
<reified>
non-reified
fun <T : Fruit> eat(fruitClass: KClass<T>)
would be callable, of course
v
Oh. Much sadness. I'm trying to avoid a lot of duplication of code which is basically of the form:
Copy code
when(food) {
  "org.me.apple" -> { eat<Apple>() }
  "org.me.pear" -> { eat<Pear>() }
}
Except the functions are a bit more involved than just
eat()
.
a
you can also use
inline
to be able to get the type