6

Using Kotlin how can a declare and call a function that takes a list of functions as a parameter. I've used parameters in functions that are a single function, but how do I do this for a list of functions?

This question shows how to send a single function to a function: Kotlin: how to pass a function as parameter to another? What would be the best way to do this for a list of functions?

James Elkwood
  • 155
  • 1
  • 4
  • 10

1 Answers1

11

You can declare it using vararg. In this example, I declare a variable number of functions that take and 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
}

Or the same thing, as a 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
    )
}
Todd
  • 30,472
  • 11
  • 81
  • 89