Search code examples
kotlinlambdavariadic-functions

vararg parameter in a Kotlin lambda


I'd like to define a function f() as follows (just an example) :

val f: (vararg strings: String) -> Unit = { for (str in it) println(str) }

so that I could invoke it with f("a","b","c"). For the above definition of f() I get the compilation error, pointing at the vararg modifier (Kotlin v. 1.3.60 ) :

Unsupported [modifier on parameter in function type]

How can I define a lambda that accepts a vararg parameter ?


Solution

  • I'm afraid this is not possible. The following demonstrates the type of a function with vararg. A vararg parameter is represented by an Array:

    fun withVarargs(vararg x: String) = Unit
    
    val f: KFunction1<Array<out String>, Unit> = ::withVarargs
    

    This behavior is also suggested in the docs:

    Inside a function a vararg-parameter of type T is visible as an array of T, i.e. the ts variable in the example above has type Array<out T>.

    So you had to use an Array<String> in your example. Instead of writing your function as a lambda, you may use an ordinary function that allows to use vararg and make the call look as desired:

    fun f(vararg strings: String) = strings.forEach(::println)
    
    f("a","b","c")