Can anybody explain me how to compare KClasse-s and interfaces among yourselves? I known how to check that classes or interfaces are equal but I don't understand how to check that A class is superclass of B class, etc.
interface IB {}
interface IC : IB {}
open class A {}
open class B : A() {}
open class C : B(), IC {}
fun main(args: Array<String>) {
if (B::class == B::class) { println("B class is equal to B class") }
if (IB::class == IB::class) { println("IB interface is equal to IB interface") }
if (A::class ??? B::class) { println("A class is parent of B class") }
if (A::class ??? C::class) { println("A class is superclass of C class") }
if (C::class ??? IC) { println("C class is implement IC interface") }
if (IC ??? IB) { println("IC interface is implement IB interface") }
}
Kotlin reflection doesn't have an API for retrieving information about KClass
hierarchy, so the only way to check if one KClass
is superclass or subclass of another KClass
is to compare corresponding java classes:
interface IB {}
interface IC : IB {}
open class A {}
open class B : A() {}
open class C : B(), IC {}
fun main(args: Array<String>) {
if (B::class == B::class) { println("B class is equal to B class") }
if (IB::class == IB::class) { println("IB interface is equal to IB interface") }
if (A::class.java.isAssignableFrom(B::class.java)) { println("A class is parent of B class") }
if (A::class.java.isAssignableFrom(C::class.java)) { println("A class is superclass of C class") }
if (IC::class.java.isAssignableFrom(C::class.java)) { println("C class is implement IC interface") }
if (IB::class.java.isAssignableFrom(IC::class.java)) { println("IC interface is implement IB interface") }
}
UPDATE:
You can also define two extension functions that will make this kind of checks a bit nicer:
inline fun <reified L : Any, reified R : Any> isSubClassOf(): Boolean {
return R::class.java.isAssignableFrom(L::class.java)
}
inline fun <reified L : Any, reified R : Any> isSuperClassOf(): Boolean {
return L::class.java.isAssignableFrom(R::class.java)
}
fun main(args: Array<String>) {
if (isSubClassOf<B, B>()) { println("B class is equal to B class") }
if (isSubClassOf<IB, IB>()) { println("IB interface is equal to IB interface") }
if (isSuperClassOf<A, B>()) { println("A class is parent of B class") }
if (isSuperClassOf<A, C>()) { println("A class is superclass of C class") }
if (isSubClassOf<C, IC>()) { println("C class is implement IC interface") }
if (isSubClassOf<IC, IB>()) { println("IC interface is implement IB interface") }
}