Kotlin将功能列表发送给

Jam*_*ood 2 kotlin

使用Kotlin如何声明和调用以函数列表作为参数的函数。我在单个函数的函数中使用了参数,但是如何为函数列表使用参数呢?

这个问题说明了如何将一个函数发送给一个函数:Kotlin:如何将一个函数作为参数传递给另一个函数?对于功能列表,执行此操作的最佳方法是什么?

Tod*_*odd 5

您可以使用声明它vararg。在此示例中,我声明了数量可变的take和return函数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
}
Run Code Online (Sandbox Code Playgroud)

或同一件事,如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
    )
}
Run Code Online (Sandbox Code Playgroud)