kotlin - 传递方法参考功能

时间:2018-02-09 15:59:47

标签: reflection jvm kotlin method-reference

我们说我有以下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中解决它?

2 个答案:

答案 0 :(得分: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 */}

这会将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 */}

答案 1 :(得分:3)

您实际上可以按照以下方式执行此操作:

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)
相关问题