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中传递方法参考(而无需重新反射的重锤(:

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()表示法调用它。它只是使用方法参考语法。

还有另一种适用于同一调用语法的表格,但使 A更加明确:

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

您实际上可以完全像您想要的那样做:

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)

最新更新