到目前为止,我尝试过使用单个参数进行回调,它可以正常工作:
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) {
// ...
}
}
答案 0 :(得分:1)
只需使用带有显式参数的lambda expression syntax:
val something = SomeClass { num, str -> onSomething(num, str) }
当传递lambda作为最后一个参数时,可以省略括号。
此外,当预期和实际功能签名完全匹配时,您可以使用bound function reference:
val something = SomeClass(this::onSomething)