Search code examples
kotlinkotlin-reflect

Check if class is a valid value for KParameter


Given the following example code

fun function(text: CharSequence) {
    println(text)
}

val textParam = ::function.parameters[0]
val stringClass = String::class

How can I check if textParam accepts stringClass as a parameter?


Solution

  • You can do the following with KClass:

    val paramClass = ::function.parameters[0].type.jvmErasure
    
    println(stringClass.isSubclassOf(paramClass))
    

    Alternatively, another solution with checking KType:

    val paramType = ::function.parameters[0].type
    
    println(stringClass.starProjectedType == paramType ||  // type is String
            stringClass.allSupertypes.contains(paramType)) // type is a supertype of String