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

后端 未结 10 2218
有刺的猬
有刺的猬 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:27

    About the member function as parameter:

    1. Kotlin class doesn't support static member function, so the member function can't be invoked like: Operator::add(5, 4)
    2. Therefore, the member function can't be used as same as the First-class function.
    3. A useful approach is to wrap the function with a lambda. It isn't elegant but at least it is working.

    code:

    class Operator {
        fun add(a: Int, b: Int) = a + b
        fun inc(a: Int) = a + 1
    }
    
    fun calc(a: Int, b: Int, opr: (Int, Int) -> Int) = opr(a, b)
    fun calc(a: Int, opr: (Int) -> Int) = opr(a)
    
    fun main(args: Array) {
        calc(1, 2, { a, b -> Operator().add(a, b) })
        calc(1, { Operator().inc(it) })
    }
    

提交回复
热议问题