Kotlin 将函数列表发送到

标签 kotlin

使用 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/

相关文章:

kotlin - 使用 Jetpack Compose 进行参数导航

kotlin - Kotlin 中 UInt 中位标志的 EnumSet

android-studio - 在Android Studio中使用导航框架时,如何知道保留的类名或关键字?

Android db文件被复制但无法打开

android - "Cannot access database on the main thread since it may potentially lock the UI for a long period of time"启动协程时出错

java - 安卓Q : SQLite database in scoped storage

android - 添加安全参数时导航方向类未更新

java - KTor 还是 Spark?哪个已为 Kotlin Web 服务做好生产准备?

android - "only const val can be used in constant expressions"编译时错误 Dagger2 Kotlin

kotlin - 检查数组是否包含子字符串?