给定函数foo:

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

我们可以:

foo("a message", { println("this is a message: $it") } )
//or 
foo("a message")  { println("this is a message: $it") }

现在,假设我们有以下函数:

fun buz(m: String) {
   println("another message: $m")
}

是否有一种方法,我可以通过“buz”作为参数“foo”? 喜欢的东西:

foo("a message", buz)

当前回答

如果你想传递setter和getter方法。

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

用法:

private var width: Int = 1

setData({ width = it }, { width })

其他回答

如果你想传递setter和getter方法。

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

用法:

private var width: Int = 1

setData({ width = it }, { width })

只需在方法名之前使用“::”

fun foo(function: () -> (Unit)) {
   function()
}

fun bar() {
    println("Hello World")
}

输出:Hello World (::bar

显然这还不被支持。

更多信息:

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

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

另一个例子:

 fun foo(x:Int, Multiply: (Int) -> (Int)) {
    println(Multiply(x))
 }
 fun bar(x:Int):Int{
    return  x * x
 }
 foo(10, ::bar)

Kotlin 1.1

使用::引用方法。

like

    foo(::buz) // calling buz here

    fun buz() {
        println("i am called")
    }