samedi 23 février 2019

How to safely cast a reflected class in Kotlin

I need to dynamically load classes at runtime in Kotlin. I would like to check that they implement my interface, and if so, all green. Unfortunately, Kotlin's "smart casts" is failing me:

var className = "some.class.Name"
val unsafeClass = Class.forName(className).kotlin
require(unsafeClass.isSubclassOf(MyInterface::class)) {
    "Class '$className' is not a MyInterface"
}
val safeClass = unsafeClass as KClass<MyInterface>
                            ^^^^^^^^^^^^^^^^^^^^^^
                            Unchecked cast: KClass<out Any!> to KClass<MyInterface>

I'm clearly checking that the class implements the given interface. Can I re-phrase this code to avoid the warning?

I tried to test with is KClass<MyInterface> but I get a type erasure error.





Aucun commentaire:

Enregistrer un commentaire