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

查看:39
本文介绍了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(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 起,您现在可以使用类成员(绑定可调用引用"),通过在函数引用操作符前加上实例:

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天全站免登陆