https://kotlinlang.org logo
a

antonkeks

01/18/2020, 11:45 AM
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()) } }
Or even better:
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 🙂
Meaning that I can't change the signature of the method
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))
2 Views