Search code examples
kotlinreflectioninterface

How can I check if a class implements an interface in Kotlin?


I have a class c stored in a variable foo. I know that if I had an object of class c I could check if it implemented an interface like this:

cInstance is someInterface

but since the type of foo is Class<*>, this will always be false if I replace cInstance with foo. How can I check if the value of foo implements someInterface?


Solution

  • Java API

    If you have a java.lang.Class object, then you can use Class::isAssignableFrom(Class).

    val type: Class<*> = ...
    val isSubtype = InterfaceType::class.java.isAssignableFrom(type)
    

    This will obviously only work on Kotlin/JVM.


    Kotlin/JVM API

    If you have a kotlin.reflect.KClass object, then you can use KClass::isSubclassOf(KClass) or KClass::isSuperclassOf(KClass).

    val type: KClass<*> = ...
    val isSubtype = type.isSubclassOf(InterfaceType::class)
    

    Though note those two functions are from kotlin-reflect. In other words, you will need to add the full reflection dependency to use those functions and they are only available on Kotlin/JVM.


    Kotlin/JS, Kotlin/Wasm, & Kotlin/Native API

    I'm not aware of any reflection-based API for testing if a KClass is a subclass of another that's available on these three platforms.