https://kotlinlang.org logo
#reflect
Title
# reflect
i

Ian Stewart

04/01/2020, 11:37 PM
Hi; I’m trying to access the argument names of a function as a KType. If I println the ktype, I get
Copy code
(url: kotlin.String, cont: (result: kotlin.String) -> kotlin.Unit) -> kotlin.Unit
…so the information is there, at least internally. Is there any way of getting the ‘url’ and ‘cont’ strings out? I am able to get the types from the arguments() method. I have read about using .reflect() to get a KFunction, but I cannot find a good example of how to do this. for myktype.classifier.reflect(), I get:
Copy code
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public fun <R> Function<TypeVariable(R)>.reflect(): KFunction<TypeVariable(R)>? defined in kotlin.reflect.jvm
d

diesieben07

04/02/2020, 8:37 AM
How are you obtaining this
KType
?
i

Ian Stewart

04/02/2020, 3:54 PM
Hi Take; e.g.
Copy code
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.jvm.reflect

class MyClass {
    public fun callMe(cont: (result: String) -> Unit): Unit {
      cont("Hello")
    }
}

public fun main() {
  (MyClass::class).declaredMemberFunctions.forEach {
    val kTyped = it.parameters.get(1).type;
    println(kTyped)
  }
}
prints ‘(result: kotlin.String) -> kotlin.Unit’
d

diesieben07

04/02/2020, 4:40 PM
Copy code
kTyped.arguments[0].type?.findAnnotation<ParameterName>()?.name
Will obtain
"result"
. The
KType
for a function will have type arguments (
(String) -> Unit
is really
Function1<String, Unit>
under the hood). Those type arguments can have a
ParameterName
annotation, if the name is known.
I.e. the actual type would be
Function1<@ParameterName("result") String, Unit>
.
👍 1
i

Ian Stewart

04/02/2020, 5:11 PM
Excellent, thank you, works perfectly.
5 Views