Right now I am using this line:
klass = Class.forName({MyClassName}).kotlin as KClass<{MySuperClassName}>
But I am getting an 'unchecked cast' warning
Is there a better way to do it?
Right now I am using this line:
klass = Class.forName({MyClassName}).kotlin as KClass<{MySuperClassName}>
But I am getting an 'unchecked cast' warning
Is there a better way to do it?
I don't see a way to avoid this warning because .kotlin
is an extension of <T : Any> Class<T>
and that's what Class.forName()
is returning (when translated from Java). So what you're actually doing looks like this:
Class.forName() -> Class<T: Any>.kotlin -> KClass<T: Any> as KClass<{MySuperClassName}>
You are casting KClass<T: Any>
to KClass<{MySuperClassName}>
and that will always produce a warning because the compiler can't tell if MySuperClassName
is in fact a descendant of T
because T
can be anything at this point.
This cast is actually incorrect; a Class<{MyClassName}>
is not a Class<{MySuperClassName}>
. It only doesn't throw an exception because, as the warning says, the cast is unchecked. The type you probably want is Class<out {MySuperClassName}>
(meaning basically Class<some subtype of {MySuperClassName}>
).
Fixing the type won't fix the warning for reason already explained in Sir Codesalot's answer.
But you can suppress the warning with @Suppress("UNCHECKED_CAST")
because no, there is no better way to do it.