kotlin – 通过函数的方法引用

比方说,我有以下的Java类:

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

然后,在我的Kotlin代码中:

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

我希望能够选择在myFunction内部调用哪个methodX。 在Java中,我会传递A::method7作为参数并调用它。 在Kotlin它不编译。 我应该如何解决在Kotlin?

您也可以通过Kotlin中的方法参考(不需要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 */} 

这将method声明为A一部分,这意味着您可以使用普通的object.method()表示法来调用它。 它只是与方法参考语法。

还有另一种forms可以使用相同的调用语法,但使得A更明确:

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

你实际上可以像你想的那样完成这个工作:

 fun myFunction(kFunction: KFunction2) { val parameter = "string" val result: Result = kFunction(A(), parameter) //... } myFunction(A::method1) myFunction(A::method2)