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

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

    You can also do this inline using a lambda if that is the only place you are using that function

    fun foo(m: String, bar: (m: String) -> Unit) {
        bar(m)
    }
    
    foo("a message") {
        m: String -> println("another message: $m")
    }
    //Outputs: another message: a message
    
    0 讨论(0)
  • 2020-11-28 05:19

    apparently this is not supported yet.

    more info:

    http://devnet.jetbrains.com/message/5485180#5485180

    http://youtrack.jetbrains.com/issue/KT-1183

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

    Just use "::" before method name

    fun foo(function: () -> (Unit)) {
       function()
    }
    
    fun bar() {
        println("Hello World")
    }
    

    foo(::bar) Output : Hello World

    0 讨论(0)
  • 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 })
    
    0 讨论(0)
  • 2020-11-28 05:26

    Another example:

     fun foo(x:Int, Multiply: (Int) -> (Int)) {
        println(Multiply(x))
     }
     fun bar(x:Int):Int{
        return  x * x
     }
     foo(10, ::bar)
    
    0 讨论(0)
  • 2020-11-28 05:27

    Use :: to signify a function reference, and then:

    fun foo(m: String, bar: (m: String) -> Unit) {
        bar(m)
    }
    
    // my function to pass into the other
    fun buz(m: String) {
        println("another message: $m")
    }
    
    // someone passing buz into foo
    fun something() {
        foo("hi", ::buz)
    }
    

    Since Kotlin 1.1 you can now use functions that are class members ("Bound Callable References"), by prefixing the function reference operator with the instance:

    foo("hi", OtherClass()::buz)
    
    foo("hi", thatOtherThing::buz)
    
    foo("hi", this::buz)
    
    0 讨论(0)
提交回复
热议问题