Home > Net >  How to declare function type for function with variable number of parameters in Kotlin
How to declare function type for function with variable number of parameters in Kotlin

Time:04-27

I am writing a function that accepts another function and it's arguments, for calling it later. How do I specify the type of function so that it can have any number of arguments?

Looking for something like this.

// this does not compile
fun doLater(func: (vararg) -> Double, args: List<Any>) {
    ...
} 

fun footprintOne(i: int, s: String): Double {...}
fun footprintTwo(cheeses: List<Cheese>): Double {...}

// these should be able to run fine
doLater(::footprintOne, listOf(3, "I love StackOverflow"))
doLater(::footprintTwo, listOf(listOf(blueCheese, bree, havarti)))

CodePudding user response:

Seems like it isn't possible. vararg parameter in a Kotlin lambda

My best workaround I can suggest is to re-wrap the function into one that takes Array or List for the varargs and take that instead.

CodePudding user response:

You'll want to use the vararg keyword:

fun doLater(func: (Array<out Any>) -> Double, vararg args: Any) {
    func(args)
}

then you call it like this:

doLater(
    { args ->
        // Function logic
    },
    1, 2, 3
)

https://kotlinlang.org/docs/functions.html#variable-number-of-arguments-varargs

  • Related