首页 文章

Kotlin发送功能列表

提问于
浏览
2

使用Kotlin如何声明和调用将函数列表作为参数的函数 . 我在单个函数的函数中使用了参数,但是如何为函数列表执行此操作?

此问题显示如何将单个函数发送到函数:Kotlin: how to pass a function as parameter to another?对于函数列表执行此操作的最佳方法是什么?

1 回答

  • 4

    您可以使用 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
        )
    }
    

相关问题