Kotlin Varargs

Read my post about functions before this. Kotlin supports a variable number of arguments (varargs). That means, when you write a function, you can make it in such a way that it accepts any number of arguments.

kotlin varargs
fun main(args: Array<String>) {
    printNames()
    printNames("Kale")
    printNames("Kale","Kate")
    printNames("Kale", "Kate","Ashley")
}

fun printNames(vararg names : String) {
    for(name in names)
        println("Name : $name")
    println()
}

See the above example. The keyword vararg is used to denote variable length argument. While writing a function we don’t know how many arguments will be passed. We then iterate over the variable length argument, which is a list of Strings.

It is also possible to extract the individual arguments using the get function.
Like this:

fun main(args: Array<String>) {
    printNames("Kale", "Kate","Ashley")
}

fun printNames(vararg names : String) {
    println("Name = ${names.get(0)}")
    println("Name = ${names.get(1)}")
    println("Name = ${names.get(2)}")
}

The problem is that, we never know how many arguments we are going to receive in the function. So, it’s always a nice idea to iterate using a for loop.

We can mix normal arguments and varargs. It works fine.
See this:

fun main(args: Array<String>) {
    printNames(4,"Kale", "Kate","Ashley")
}

fun printNames(firstArg : Int, vararg names : String) {
    println("First argument. Not variable length : $firstArg")
    println("Name = ${names.get(0)}")
    println("Name = ${names.get(1)}")
    println("Name = ${names.get(2)}")
}

Here the parameter firstArg is the normal type of argument. We are using a vararg after that. In this case, when the function is called, we must supply the first argument, because it’s not optional.

« Back to the index of Kotlin tutorial

Add a Comment

Your email address will not be published. Required fields are marked *