Kotlin函数类型代替函数接口lambda

时间:2017-07-02 22:55:40

标签: lambda kotlin

我在kotlin中努力与java中的功能接口相反。我有以下问题。

class ResultReceiverTest(handler : Handler) : ResultReceiver(handler) {

    fun onResult(result : (resultCode : Int, resultData: Bundle) -> Unit){
        // result() how to receive values from onReceiveResult() method?
    }

    override fun onReceiveResult(resultCode: Int, resultData: Bundle){
        // how to call onResult from here?
        // I want to pass resultCode, resultData parameter to onResult function
    }
}

我遇到以下情况,首先调用onReceiveResult然后我想将onReceiveResult的参数值传递给onResult,这样我才能通过result()的值,由以下类实现。

class StartService {
    private var resultReceiverTest = ResultReceiverTest(Handler())

    init{
        resultReceiverTest.onResult({a, b -> something()})
    }


    fun something(){}
}

那么我如何将onReceiveResult的价值提供给onResult?我知道kotlin中的功能接口和匿名类解决方案。但是我想用lambda实现它,这对我理解lambda也很有帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用属性来保存处理程序。

class ResultReceiverTest(handler : Handler) : ResultReceiver(handler) {
    private var resultHandler: ((resultCode : Int, resultData: Bundle) -> Unit)? = null

    fun onResult(result : (resultCode : Int, resultData: Bundle) -> Unit){
        resultHandler = result
    }

    override fun onReceiveResult(resultCode: Int, resultData: Bundle){
        resultHandler?.invoke(resultCode, resultData)
    }
}

答案 1 :(得分:1)

为什么不做这样的事情?在初始化期间提供on结果回调:

class ResultReceiverTest(handler: Handler, private val onResult: (Int, Bundle) -> Unit) : ResultReceiver(handler) {
  override fun onReceiveResult(resultCode: Int, resultData: Bundle) {
    onResult(resultCode, resultData)
  }
}

// Do it with a function reference
class StartService {

  private var resultReceiverTest = ResultReceiverTest(Handler(), this::doSomethingWithResult)

  fun doSomethingWithResult(resultCode: Int, resultData: Bundle) {
    println(resultCode)
  }
}

// OR DO IT INLINE
class StartService {

  private var resultReceiverTest = ResultReceiverTest(Handler()) { resultCode, resultData -> println(resultCode) }

}