1

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?

Mibac
  • 8,990
  • 5
  • 33
  • 57

1 Answers1

3

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
zsmb13
  • 85,752
  • 11
  • 221
  • 226