给定函数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目前不支持第一类函数。关于这是否是一个好的功能存在争论,我个人认为他们应该这样做。

显然这还不被支持。

更多信息:

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

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

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

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)

关于作为形参的成员函数:

Kotlin类不支持静态成员函数,因此不能像这样调用成员函数: 接线员::添加(5,4) 因此,成员函数不能像头等函数那样使用。 一个有用的方法是用lambda来包装函数。它并不优雅,但至少在工作。

代码:

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) })
}

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

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

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

输出:Hello World (::bar

Kotlin 1.1

使用::引用方法。

like

    foo(::buz) // calling buz here

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

如果你想传递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 })

Jason Minard的回答很好。这也可以使用lambda来实现。

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

val buz = { m: String ->
    println("another message: $m")
}

可以用foo("a message", buz)调用。

您还可以使用类型别名使其更加DRY。

typealias qux = (m: String) -> Unit

fun foo(m: String, bar: qux) {
    bar(m)
}

val buz: qux = { m ->
    println("another message: $m")
}

另一个例子:

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

您也可以使用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 main(){
    result(10,3,::multiplication)// pass function as parameter wow kotlin amazing
}
fun multiplication(first:Int,second:Int):Int{
    return first*second
}
fun result(firstOne:Int,secondOne: Int,fn:(Int,Int)->Int){
    val result=fn(firstOne,secondOne)
    print(result)

}