Keverly
Keverly

Reputation: 518

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

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)))

Upvotes: 1

Views: 1388

Answers (2)

MFazio23
MFazio23

Reputation: 1312

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

Upvotes: 1

Alex G
Alex G

Reputation: 26

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.

Upvotes: 1

Related Questions