Search code examples
javakotlinvariadic-functionsellipsis

Ellipsis operator Java equivalence in Kotlin


In Java, it is possible to do something like this: void function(Url... urls). It makes possible to use 1..n urls. The question is if it is possible to do the same thing with Kotlin.


Solution

  • From the Kotlin reference (https://kotlinlang.org/docs/reference/functions.html):

    Variable number of arguments (Varargs)

    A parameter of a function (normally the last one) may be marked with vararg modifier:

    fun <T> asList(vararg ts: T): List<T> {
        val result = ArrayList<T>()
        for (t in ts) // ts is an Array
            result.add(t)
        return result
    }
    

    allowing a variable number of arguments to be passed to the function:

    val list = asList(1, 2, 3)
    

    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.

    Beware of a difference with Java: in Java you can pass an array as single parameter, while in Kotlin you must explicitly unpack the array, so that every array element becomes a separate argument. But you can do it by simply putting the * character before the corresponding argument:

    fun main(args: Array<String>) {
        val list = listOf("args: ", *args)
        println(list)
    }
    

    (See how it lets you combine the values from an array and some fixed values in a single call, which is not allowed in Java).