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

当前回答

Kotlin 1.1

使用::引用方法。

like

    foo(::buz) // calling buz here

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

其他回答

使用::表示函数引用,然后:

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

// my function to pass into the other
fun buz(input: String) {
    println("another message: $input")
}

// someone passing buz into foo
fun something() {
    foo("hi", ::buz)
}

从Kotlin 1.1开始,你现在可以使用作为类成员的函数(“绑定可调用引用”),方法是在函数引用操作符前加上实例:

foo("hi", OtherClass()::buz)

foo("hi", thatOtherThing::buz)

foo("hi", this::buz)

您也可以使用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

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

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)