Kotlin:如何将函数作为参数传递给另一个函数? [英] Kotlin: how to pass a function as parameter to another?

查看:1717
本文介绍了Kotlin:如何将函数作为参数传递给另一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

现在,可以说我们具有以下功能:

Now, lets say we have the following function:

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

有没有一种方法可以将"buz"作为参数传递给"foo"? 像这样:

Is there a way I can pass "buz" as a parameter to "foo" ? Something like:

foo("a message", buz)

推荐答案

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

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

自Kotlin 1.1起,您现在可以使用以下功能:类成员("可调用的绑定引用"),方法是在函数引用运算符前添加实例:

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)

这篇关于Kotlin:如何将函数作为参数传递给另一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆