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?

1 Answer 1

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
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.