代码之家  ›  专栏  ›  技术社区  ›  piotrek

kotlin-将方法引用传递给函数

  •  10
  • piotrek  · 技术社区  · 8 年前

    假设我有以下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
    }
    

    我希望能够选择在内部调用哪个methodX myFunction . 在Java中,我会通过 A::method7 作为一个论据并调用它。在Kotlin中,它不会编译。我应该如何在Kotlin解决它?

    2 回复  |  直到 8 年前
        1
  •  13
  •   chris    8 年前

    您还可以在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 */}
    
        2
  •  3
  •   s1m0nw1    8 年前

    实际上,您可以完全按照自己的意愿进行:

    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)