使用 Kotlin 如何声明和调用以函数列表作为参数的函数。我在作为单个函数的函数中使用了参数,但是如何为函数列表执行此操作?
这个问题显示了如何将单个函数发送到一个函数:Kotlin: how to pass a function as parameter to another?对函数列表执行此操作的最佳方法是什么?
最佳答案
您可以使用 vararg
声明它.在这个例子中,我声明了一个可变数量的函数,这些函数接受并返回 String
.
fun takesMultipleFunctions(input: String, vararg fns: (String) -> String): String =
fns.fold(input){ carry, fn -> fn(carry) }
fun main(args: Array<String>) {
println(
takesMultipleFunctions(
"this is a test",
{ s -> s.toUpperCase() },
{ s -> s.replace(" ", "_") }
)
)
// Prints: THIS_IS_A_TEST
}
或者同样的事情,作为
List
:fun takesMultipleFunctions(input: String, fns: List<(String) -> String>): String =
fns.fold(input){ carry, fn -> fn(carry) }
fun main(args: Array<String>) {
println(
takesMultipleFunctions(
"this is a test",
listOf(
{ s -> s.toUpperCase() },
{ s -> s.replace(" ", "_") }
)
)
// Prints: THIS_IS_A_TEST
)
}
关于Kotlin 将函数列表发送到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49904755/