kotlin - 传递方法参考功能

pio*_*rek 4 reflection jvm kotlin method-reference

假设我有以下Java类:

public class A {
   public Result method1(Object o) {...}
   public Result method2(Object o) {...}
   ...
   public Result methodN(Object o) {...}
}
Run Code Online (Sandbox Code Playgroud)

然后,在我的Kotlin代码中:

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

我希望能够选择在里面调用哪个methodX myFunction.在Java中,我会将其A::method7作为参数传递并调用它.在Kotlin它没有编译.我应该如何在Kotlin解决它?

chr*_*ris 6

你也可以在Kotlin中传递方法参考(不需要反射的重锤):

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 */}
Run Code Online (Sandbox Code Playgroud)

这声明method为部分A,意味着您可以使用正常object.method()表示法调用它.It Just Works™使用方法参考语法.

还有另一种形式使用相同的调用语法,但A更明确:

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

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