gpt4 book ai didi

Kotlin:如何将一个函数作为参数传递给另一个函数?

转载 作者:IT老高 更新时间:2023-10-28 13:26:00 25 4
gpt4 key购买 nike

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

最佳答案

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

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

Since Kotlin 1.1您现在可以使用作为类成员的函数(“Bound Callable References”),方法是在函数引用运算符前面加上实例:

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

foo("hi", thatOtherThing::buz)

foo("hi", this::buz)

关于Kotlin:如何将一个函数作为参数传递给另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16120697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com