kotlin - 将方法引用传递给函数
kotlin - Pass method reference to function
假设我有以下 Java class:
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 中解决它?
您实际上可以完全按照自己的意愿执行此操作:
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)
也可以通过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 */}
假设我有以下 Java class:
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 中解决它?
您实际上可以完全按照自己的意愿执行此操作:
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)
也可以通过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 */}