Graham
Graham

Reputation: 5884

Lambda type with unknown number of arguments

I have created a map that will store functions to be called at a later time, its type looks like this:

Map<String, () -> Unit>

The thing is, I don't know how many parameters each function being stored has, or the types of those parameters.

Currently the map type Map<String, () -> Unit> will only let me store functions that have no parameters and a return type of Unit.

How do I represent a function type that will let me store functions with an unknown number of parameters and an unknown return type, but it still has to be a function that is stored.

Something like this is what I'm looking for:

Map<String, (T, X, Y, ...) -> V>

How do I represent that kind of function type in Kotlin?

Upvotes: 3

Views: 909

Answers (2)

voddan
voddan

Reputation: 33769

All functional types in Kotlin implement Function(https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-function.html), so you can use it or its subclass

Upvotes: 4

voddan
voddan

Reputation: 33769

You can pass the parameters in a list:

Map<String, (List<Any>) -> Unit>

Upvotes: 2

Related Questions