【问题标题】:Callback to constructor with multiple parameters使用多个参数回调构造函数
【发布时间】:2018-03-21 05:31:23
【问题描述】:

到目前为止,我尝试的是使用单个参数进行回调,并且可以正常工作:

class SomeClass (something:Int = 3, val callback: (Int) -> Unit) {
    fun doSomething() {
      callback(11)
    }
}

class AnotherClass {

    val something = SomeClass({onSomething(it)}) 

    protected fun onSomething(num: Int) {
        // ...
    }
}

但是如何使用多个参数来实现它,例如:

class SomeClass (something:Int = 3, val callback: (Int, String) -> Unit) {
    fun doSomething() {
      callback(11, "Yeah")
    }
}

class AnotherClass {

    val something = SomeClass(/* ...... what goes here???? */) 

    protected fun onSomething(num: Int, str: String) {
        // ...
    }
}

【问题讨论】:

    标签: class parameters constructor callback kotlin


    【解决方案1】:

    只需使用带有显式参数的lambda expression syntax

    val something = SomeClass { num, str -> onSomething(num, str) }
    

    当传递一个 lambda 作为最后一个参数时,可以省略括号。

    此外,当预期和实际函数签名完全匹配时,您可以使用 bound function reference

    val something = SomeClass(this::onSomething)
    

    【讨论】:

      猜你喜欢
      • 2013-02-17
      • 2013-10-03
      • 1970-01-01
      • 2012-07-28
      • 2018-12-06
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多