functionkotlindefault-valuevariadic-functionsnamed-parameters

Kotlin: Can you use named arguments for varargs?


For example, you might have function with a complicated signature and varargs:

fun complicated(easy: Boolean = false, hard: Boolean = true, vararg numbers: Int)

It would make sense that you should be able to call this function like so:

complicated(numbers = 1, 2, 3, 4, 5)

Unfortunately the compiler doesn't allow this.

Is it possible to use named arguments for varargs? Are there any clever workarounds?


Solution

  • It can be worked around by moving optional arguments after the vararg:

    fun complicated(vararg numbers: Int, easy: Boolean = false, hard: Boolean = true) = {}
    

    Then it can be called like this:

    complicated(1, 2, 3, 4, 5)
    complicated(1, 2, 3, hard = true)
    complicated(1, easy = true)
    

    Note that trailing optional params need to be always passed with name. This won't compile:

    complicated(1, 2, 3, 4, true, true) // compile error
    

    Another option is to spare vararg sugar for explicit array param:

    fun complicated(easy: Boolean = false, hard: Boolean = true, numbers: IntArray) = {}
    
    complicated(numbers = intArrayOf(1, 2, 3, 4, 5))