I have class
class Generic()
and this code is\'t correct
fun typeCheck(s: SuperType): Unit {
If you need to check if something is of generic type T you need to to have an instance of Class 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(val klass: Class) {
companion object {
inline operator fun 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().checkType("foo")
Generic().checkType(1)
}