Madhu Bhat
Madhu Bhat

Reputation: 15173

Kotlin | Find param of a function which returns a lambda using the lambda

Say I have a function haveFun which takes in a Method (from java.lang.reflect package) as a param and returns a lambda as below

typealias AnyFun = (o: Any?) -> Any?

fun haveFun(method: Method): AnyFun {
    return { o -> method.invoke(o) }
}

data class Game(val name: String)

Now if I pass a method to the function and assign the lambda to a field as

val game = haveFun(Game::name.javaGetter!!)

Can I find out and access the Method that was passed to the function using the above game field which is a lambda?

I can see the Method while debugging on Intellij, but not sure on how to access it.

enter image description here

Upvotes: 1

Views: 556

Answers (1)

Pietro Martinelli
Pietro Martinelli

Reputation: 1906

You can access and use it through reflection as a declaredField having $method name, as follows:

val methodField = game.javaClass.getDeclaredField("\$method")
val method = methodField.get(game) as Method
println(method.invoke(Game("Pietro"))) // outputs the String "Pietro"

Upvotes: 2

Related Questions