1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Oh dear, it seems I didn't write my question clear enough. I'll try to update it

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.