Kotlin: how to pass a function as parameter to another?

后端 未结 10 2106
有刺的猬
有刺的猬 2020-11-28 04:54

Given function foo :

fun foo(m: String, bar: (m: String) -> Unit) {
    bar(m)
}

We can do:

foo(\"a message\", { println         


        
10条回答
  •  有刺的猬
    2020-11-28 05:25

    If you want to pass setter and getter methods.

    private fun setData(setValue: (Int) -> Unit, getValue: () -> (Int)) {
        val oldValue = getValue()
        val newValue = oldValue * 2
        setValue(newValue)
    }
    

    Usage:

    private var width: Int = 1
    
    setData({ width = it }, { width })
    

提交回复
热议问题