piotrek
piotrek

Reputation: 14550

kotlin - Pass method reference to function

Let's say I have the following Java class:

public class A {
   public Result method1(Object o) {...}
   public Result method2(Object o) {...}
   ...
   public Result methodN(Object o) {...}
}

Then, in my Kotlin code:

fun myFunction(...) {
    val a: A = ...
    val parameter = ...
    val result = a.method1(parameter) // what if i want methodX?
    do more things with result
}

and I want to be able to choose which methodX will be called inside myFunction. in Java, I would pass A::method7 as an argument and call it. in Kotlin it doesn't compile. How should I solve it in Kotlin?

Upvotes: 10

Views: 6463

Answers (2)

Qaz
Qaz

Reputation: 61920

You can also pass the method reference in Kotlin (without needing the heavy hammer that is reflection):

fun myFunction(method: A.(Any) -> Result) {
    val a: A = ...
    val parameter = ...
    val result = a.method(parameter)
    do more things with result
}

myFunction(A::method1)
myFunction {/* do something in the context of A */}

This declares method as part of A, meaning you can call it with normal object.method() notation. It Just Works™ with the method reference syntax.

There's also another form that works with the same call syntax, but makes A more explicit:

fun myFunction(method: (A, Any) -> Result) { ... }

myFunction(A::method1)
myFunction {a, param -> /* do something with the object and parameter */}

Upvotes: 14

s1m0nw1
s1m0nw1

Reputation: 81929

You can actually do this exactly like you wanted to:

fun myFunction(kFunction: KFunction2<A, @ParameterName(name = "any") Any, Result>) {
    val parameter = "string"
    val result: Result = kFunction(A(), parameter)
    //...
}

myFunction(A::method1)
myFunction(A::method2)

Upvotes: 3

Related Questions