给定函数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 })

其他回答

显然这还不被支持。

更多信息:

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

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

您也可以使用lambda内联执行此操作,如果这是惟一使用该函数的地方

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

foo("a message") {
    m: String -> println("another message: $m")
}
//Outputs: another message: a message

Kotlin目前不支持第一类函数。关于这是否是一个好的功能存在争论,我个人认为他们应该这样做。

Kotlin 1.1

使用::引用方法。

like

    foo(::buz) // calling buz here

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

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

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

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

输出:Hello World (::bar