Anyone knows a proper way to make this compile (without unsafe casting)?
Copy code
fun <T: Any> register(c: KClass<T>, i: T) {}
fun main() {
listOf(ArrayList::class, LinkedList::class).forEach { // any different classes here
register(it, it.createInstance())
}
}
n
nikolaymetchev
01/20/2020, 1:17 AM
fun register(c: KClass<*>, i: Any) {}
fun main() {
listOf(ArrayList::class, LinkedList::class).forEach {
register(it, it.createInstance())
}
}
nikolaymetchev
01/20/2020, 1:23 AM
Or even better:
nikolaymetchev
01/20/2020, 1:23 AM
fun register(i: Any) {
val c = i.javaClass.kotlin
}
fun main() {
listOf(ArrayList::class, LinkedList::class).forEach {
register(it.createInstance())
}
}
a
antonkeks
01/20/2020, 9:18 PM
Thanks for ideas! The example is actually from the Jooby framework,
services.put()
method that is implemented in Java and I was wondering, why can't I call it from Kotlin 🙂
antonkeks
01/20/2020, 9:18 PM
Meaning that I can't change the signature of the method
antonkeks
01/20/2020, 9:26 PM
The same problem is with this code:
Copy code
data class User(val name: String)
val user = User("Hello")
println(user::class.memberProperties.first().get(user))