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

后端 未结 10 2108
有刺的猬
有刺的猬 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<String>) {
        calc(1, 2, { a, b -> Operator().add(a, b) })
        calc(1, { Operator().inc(it) })
    }
    
    0 讨论(0)
  • 2020-11-28 05:27

    First-class functions are currently not supported in Kotlin. There's been debate about whether this would be a good feature to add. I personally think they should.

    0 讨论(0)
  • 2020-11-28 05:29

    Kotlin 1.1

    use :: to reference method.

    like

        foo(::buz) // calling buz here
    
        fun buz() {
            println("i am called")
        }
    
    0 讨论(0)
  • 2020-11-28 05:35

    Jason Minard's answer is a good one. This could also be achieved using a lambda.

    fun foo(m: String, bar: (m: String) -> Unit) {
        bar(m)
    }
    
    val buz = { m: String ->
        println("another message: $m")
    }
    

    Which can be called with foo("a message", buz).

    You can also make this a bit more DRY by using a typealias.

    typealias qux = (m: String) -> Unit
    
    fun foo(m: String, bar: qux) {
        bar(m)
    }
    
    val buz: qux = { m ->
        println("another message: $m")
    }
    
    0 讨论(0)
提交回复
热议问题