https://kotlinlang.org logo
#reflect
Title
# reflect
v

v79

12/15/2021, 9:23 PM
If class
Apple
extends class
Fruit
, how can I create a map like
mapOf<String,KClass<Fruit>>("apple" to Apple)
?
e

ephemient

12/15/2021, 9:24 PM
that would be a
Copy code
Map<String, KClass<out Fruit>>
as
KClass<T>
is invariant
v

v79

12/15/2021, 9:29 PM
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

ephemient

12/15/2021, 9:46 PM
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

v79

12/15/2021, 9:48 PM
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

Ayfri

12/16/2021, 5:28 PM
you can also use
inline
to be able to get the type
6 Views