I have class
class Generic<T : SuperType>()
and this code is't correct
fun typeCheck(s: SuperType): Unit { when(s){ is T -> //do some thin } }
but cast s
to type T
s as T
show warning - unsafe cast.
How check that s
is type T
?
There are no direct ways to do this in Kotlin. In order to check the generic type, we need to create an instance of the generic class<T> and then we can compare the same with our class.
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
You can use b::class. simpleName that will return type of object as String . You don't have to initialize type of a variable and later you want to check the type of variable.
In the event one generic class uses the generic type as input and output to it's function, then no in or out is used. It is invariant.
If you need to check if something is of generic type T
you need to to have an instance of Class<T>
to check against. This is a common technique in Java however in Kotlin we can make use of an inlined factory method that gets us the class object.
class Generic<T : Any>(val klass: Class<T>) { companion object { inline operator fun <reified T : Any>invoke() = Generic(T::class.java) } fun checkType(t: Any) { when { klass.isAssignableFrom(t.javaClass) -> println("Correct type") else -> println("Wrong type") } } } fun main(vararg args: String) { Generic<String>().checkType("foo") Generic<String>().checkType(1) }
Generic types are not reified on the JVM at runtime, so there's no way to do this in Kotlin. The warning is correct because the compiler can't possibly generate any instruction that will fail when the cast is done, so the cast is unchecked, meaning that the program may or may not break at some point later instead.
A related feature which might be of use is reified type parameters in inline functions. Classes can't have reified type parameters though, so if you elaborate a bit more on your use case, I can try helping you achieve what you seem to need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With