Consider the following generic class which is “reified” by using a type token:
class Gen<X : Any>(val token: KClass<X>) {
fun doSomething(x: X) {
// ...
}
}
Now Gen
is used heterogeneously using star projection but the type token can be used to match fitting values:
fun m(g: Gen<*>, x: Any) {
if (g.token == x::class) {
g.doSomething(x)
}
}
This does not compile. Introducing the following unchecked cast makes the code compile, but is unsafe as the cast value can be fed with the wrong input (the current code does not actually throw ClassCastException but can easily be extended to do so).
fun m(g: Gen<*>, x: Any) {
if (g.token == x::class) {
g as Gen<Any>
g.doSomething(x)
g.doSomething(8) // potential ClassCastException
}
}
Is this the only way to handle this or are there more type safe ways to do it?