[ACCEPTED]-Kotlin Reflection - Check if property has type-kotlin

Accepted answer
Score: 13

There are at least two solutions here:

  • Get 7 the KClass<*> of it.returnType using .jvmErasure, then check the subtype 6 relationship for the KClasses:

    it.returnType.jvmErasure.isSubclassOf(Component::class)
    
  • Since Kotlin 1.1, you 5 can construct the KType from the KClass token using 4 .createType() (check its optional parameters: you can 3 use them to provide nullability info, type 2 arguments and annotations), and then check 1 the subtype as you suggested:

    it.returnType.isSubtypeOf(Component::class.createType())
    

    Creating the type on every iteration may introduce performance issues, make sure you cache it if you need it often.

More Related questions