1
// normal function 
fun something(a: String, b: String): String {
 return "$a $b"
}
println(::something.parameters) <- not empty

but

// anonymous function 
var something = fun(a: String, b: String): String {
 return "$a $b"
}
println(::something.parameters) <- empty

how to get anonymous function parameters infomation?

j08691
209k33 gold badges269 silver badges281 bronze badges
asked Nov 23, 2024 at 20:20

1 Answer 1

3

In the second code snippet, something is a property, so ::something is a reference to the property. ::something is of type KMutableProperty0<(String, String) -> String>. You obviously don't want to get the parameters of the property.

The "function" you want is the value stored in something, so ideally you would just do something.parameters. However, something is a (String, String) -> String, not a KFunction, so you cannot do reflection on it.

There is an experimental API that gives you the KFunction representing the (String, String) -> String - reflect.

So you can do:

var something = fun(a: String, b: String): String {
 return "$a $b"
}
@OptIn(ExperimentalReflectionOnLambdas::class)
fun main() {
 println(something.reflect()?.parameters)
}

For language version (not compiler version) 2.0, lambdas and anonymous functions are now created using invokedynamic calls, and reflect cannot work with those.

For this to work in 2.0, you can annotate the function like this:

var something = @JvmSerializableLambda 
 fun(a: String, b: String): String { ... }

or use the -Xlambdas=class compiler option. Either of these will make the anonymous function compile to a class (the old behaviour before 2.0).

answered Nov 23, 2024 at 20:43
Sign up to request clarification or add additional context in comments.

2 Comments

thank you reply. but the result was different from what I expected. -> println(something.reflect()?.parameters) // null
@dbwhddn10 Ah I see. I was still using Kotlin 1.9. Kotlin 2.0 breaks this. You need to add an extra compiler flag to keep the old behaviour.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.