Lambda type with variable number of args in Kotlin?

Answer #1 100 %

This is impossible

Kotlin uses static, strong typing, and the compiler needs to know the exact type of the lambda parameters at compile time. Internally lambdas are actually implementations of one of the kotlin.jvm.functions interfaces (for JVM or Android), like this one:

/* A function that takes 1 argument. */
public interface Function1

These interfaces define the exact number of parameters and their types. Because of that it's not possible to create a vararg lambda in Kotlin. This is of course related to the fact, that vararg in JVM is just a syntax sugar that internally uses ordinary arrays, but is not a type system construct by itself, so you can't treat varargs like types.

Dependent types

One suggestion to solve your problem is to use an Array or a Collection as a function parameter, or pass in arbitrary Function, but this solution is limited in the way that there is no way for to statically enforce the same amount of the parameters of each passed function, because type system itself doesn't know about the size of collection/array or parameter count of Function.

To solve your problem entirely you need a language with dependent type system.

You’ll also like:

© 2023 -