2017-10-09 134 views
1
什麼

我試過到目前爲止回調與單一的參數,它的工作原理:回調與多個參數構造器

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) { 
     // ... 
    } 
} 

回答

1

剛使用lambda expression syntax有明確參數:

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

時,順便林bda作爲最後一個參數,可以省略括號。

此外,您還可以使用bound function reference如果預期和實際功能的簽名完全匹配:

val something = SomeClass(this::onSomething)