CodeGym /Courses /Kotlin SELF /vararg in a signature: why it exists and what the call lo...

vararg in a signature: why it exists and what the call looks like

Kotlin SELF
Level 16, Lesson 0
Available

1. Why you need vararg

Sometimes in programming a very everyday situation happens: you want to write a function that does the same action for a set of values, but you don’t know in advance how many values there will be. Today it’s 2, tomorrow it’s 5, the day after it’s 0 (yes, that happens too, and it’s not always an error).

You can, of course, force the calling code to manually build an array; you can pass “empty values” like 0 or "" (and then suffer); you can write different functions “for 2 arguments”, “for 3 arguments”… but that quickly turns into a circus.

For cases like this, Kotlin has a parameter with a variable number of arguments — vararg.

What vararg is

When you see the word vararg in a function signature, it means: “you can pass 0 or more arguments of this type to this function.” In other words, the argument count range looks like 0..N.

Formally, this is part of the Kotlin language: one parameter in the signature is marked with the vararg modifier, and Kotlin lets you call the function by listing any number of values. Inside the function, this parameter behaves like an array — we’ll get to that a bit later.

Let’s start with the most “classic” example — a sum.

2. Syntax and basic vararg calls

Minimal example: summing as many numbers as you want

Now there will be code that looks too simple — and that’s fine. Our goal is for you to see what vararg looks like and what the call looks like.

fun sumAll(vararg xs: Int): Int {
    var sum = 0
    for (x in xs) sum += x
    return sum
}

fun main() {
    println(sumAll(1, 2, 3))        // 6
    println(sumAll(10, 20))         // 30
}

Notice two things. First, vararg xs: Int sits where a normal parameter would — it’s still a “function parameter”, just a special one. Second, the call sumAll(1, 2, 3) looks like a regular function call where you listed the arguments separated by commas.

Calling with no arguments: vararg allows f()

With vararg, a small “moment of truth” almost always happens: you suddenly realize that the function can legally be called with no arguments at all. This is not a compilation error; Kotlin won’t complain. And at this point you, as the author of the function, must think: “What should my function do in that case?”

Let’s continue the sum example — for the sum of an “empty set” it makes sense to return 0.

fun sumAll(vararg xs: Int): Int {
    var sum = 0
    for (x in xs) sum += x
    return sum
}

fun main() {
    println(sumAll())               // 0
    println(sumAll(5))              // 5
}

In this example, sumAll() returns 0 not because Kotlin “decided so”, but because we wrote the code so that for an empty set it simply won’t enter the loop and will return the initial value sum.

What vararg looks like in a signature and how to read it

At this stage it’s important to learn to “read” a signature at a glance. When you see:

fun printLines(vararg lines: String) { ... }

it reads roughly like: “printLines takes any number of strings, and inside we’ll process them one by one.”

In Kotlin, vararg is usually placed closer to the end of the parameter list (often last), because that makes calls look more natural.

Let’s make a “practical” print function:

fun printLines(vararg lines: String) {
    for (line in lines) {
        println(line)
    }
}

fun main() {
    printLines("one", "two", "three")
    // one
    // two
    // three
}

And here vararg really starts to feel like a convenience: instead of manually creating an array of strings “just to print once”, you simply list the values.

3. How vararg works inside a function

What happens “under the hood”: vararg turns into an array

Now comes an important idea that helps a lot with not getting confused. When you call sumAll(1, 2, 3), Kotlin, inside the compiler, does something like this: it “packs” those numbers into an array and passes it to the function.

In practice, for us that means: inside the function you have access to familiar array things — the loop for (x in xs), the size xs.size, and indexed access xs[i].

For visualization, you can imagine the process like this:

flowchart TD
    A["Call: sumAll(1, 2, 3)"] --> B["Compiler packed into a collection"]
    B --> C["Inside the function, xs behaves like an array"]
    C --> D["The for (x in xs) loop computes the sum"]

You don’t need to memorize how exactly it’s stored in memory — it’s enough to remember the practical rule: inside the function, vararg can be iterated like an array.

vararg inside a function: size, indices, and printing

Once you’ve gotten a bit comfortable with for (x in xs), you almost immediately want to do something smarter: for example, print elements with their positions, or find out how many arguments came in. And that’s a normal desire: you’re starting to think like a developer, not like someone who just “copies the example”.

Let’s make a function that prints numbers and their count:

fun printNumbers(vararg xs: Int) {
    println("Count = ${xs.size}")
    for (i in xs.indices) {
        println("xs[$i] = ${xs[i]}")
    }
}

fun main() {
    printNumbers(7, 8, 9)
    // Count = 3
    // xs[0] = 7
    // xs[1] = 8
    // xs[2] = 9
}

Here you can see the combination from previous topics: indices on arrays and indexing xs[i]. It’s exactly the same style as in the arrays topic, except now the array “arrives” in the function via vararg.

Restriction: only one vararg per function

In Kotlin there is an important rule: only one function parameter can be marked as vararg.

This isn’t the language being “picky”, but a way to avoid ambiguity: if you could write fun f(vararg a: Int, vararg b: Int), then for the call f(1, 2, 3) it would be unclear where a ends and where b begins.

Here’s an example that will not compile:

fun broken(vararg a: Int, vararg b: Int) { // not allowed
    println(a.size + b.size)
}

The compiler won’t let you build this — and that saves you from code that can’t be called cleanly.

4. Practice: vararg in “Guess the Number”

Why vararg is useful in a project

vararg isn’t a “cute language feature”, but a tool that makes code more convenient and cleaner, especially when you print lots of messages or collect data in one place.

Imagine that in your “Guess the Number” mini-project you often write chunks like this:

println("Welcome!")
println("I picked a number.")
println("Try to guess it.")

This works, but it looks noisy: lots of print lines, and the game logic drowns in “chatter”.

Let’s make a small utility: “print several lines.” And here vararg is perfect: the number of lines is different every time.

fun say(vararg lines: String) {
    for (line in lines) {
        println(line)
    }
}

Now in main or in your game loop you can write more compactly and more readably.

Example: game greeting via say(vararg ...)

Important: the code examples will be short, but logically connected. Imagine these are fragments of one file GuessNumber.kt that you already wrote earlier.

fun say(vararg lines: String) {
    for (line in lines) println(line)
}

fun main() {
    say(
        "Welcome to the game!",
        "I picked a number.",
        "Try to guess :)"
    )
}

Notice: syntactically, this is a normal function call. There are just many arguments. Kotlin doesn’t require any brackets, arrays, or extra steps. You list the strings, and the function receives them as a “set”.

Example: hint messages as vararg

In “Guess the Number”, branching is common: we print different hints depending on the situation. And sometimes you want to print one line, sometimes two. If printing is smeared across if/else, the code quickly starts to look like holiday string lights: it’s lit up, but it’s hard to see where the wire is.

Let’s make a function that prints hints:

fun hint(vararg lines: String) {
    for (line in lines) println(line)
}

fun main() {
    val secret = 42
    val guess = 50

    if (guess > secret) {
        hint("Too high!", "Try lower.")
        // Too high!
        // Try lower.
    } else if (guess < secret) {
        hint("Too low!")
        // Too low!
    } else {
        hint("You got it!")
        // You got it!
    }
}

Here you basically made a “micro API” for messages. And it’s a nice habit: you separate “what we do” (game logic) from “how we talk” (messages to the user).

Example: debug(vararg ...) for debug printing

When you’re learning, you often insert println() just to understand “what’s happening”. That’s normal. Moreover, it’s one of the most honest ways to debug early on (before you’re comfortable with a debugger).

But if there are too many println() calls, you get noise again. You can make a tiny “logger-lite”: a function that takes a tag (a string) and a set of messages.

Important: today we’re making the simplest possible variant, where vararg comes last so the call is natural.

fun debug(tag: String, vararg messages: String) {
    for (m in messages) {
        println("[$tag] $m")
    }
}

fun main() {
    debug("GAME", "Start", "Secret generated", "Waiting for input")
    // [GAME] Start
    // [GAME] Secret generated
    // [GAME] Waiting for input
}

This gives you convenient output, and vararg lets you pass as many messages as you want in a single call.

5. vararg or an array: which to choose

Before vararg, you already had a way to pass “many values”: make the parameter an array type, for example IntArray. This is a working approach. But vararg often makes the call simpler and nicer to read.

Here’s a compact comparison:

Approach What the call looks like What’s inconvenient When it fits
fun f(xs: IntArray)
f(intArrayOf(1, 2, 3))
you need to manually create an array when the data already lives in an array
fun f(vararg xs: Int)
f(1, 2, 3)
you need to think through the case
f()
when you want a “natural” call by listing values

We’ll talk separately about the situation “the data is already in an array, but the function is vararg” in the lecture about the spread operator, because there are important syntactic nuances there. Today we won’t go into that: it’s important to simply understand the idea of vararg and get used to calling it.

6. Common mistakes when working with vararg

Mistake #1: “I thought vararg is a magical collection, but it’s like an array.”
At the beginning it’s easy to expect vararg to have some “super methods”. But in practice it’s simpler and more correct to think like this: inside the function, vararg behaves like an array, and the basic operations are for, size, and indexing.

Mistake #2: you forgot that a call with no arguments is possible, and you crashed on xs[0].
As soon as you write vararg, you automatically allow the call f(). If inside you immediately do xs[0], then for an empty set you’ll get a runtime error. Even if “that never happens in your scenario”, Kotlin still allows such a call, and you must either handle it or explicitly forbid it.

Mistake #3: you tried to declare two vararg parameters in one function.
This is a classic: you want “a list of numbers and a list of strings”, but Kotlin won’t allow it — there can be only one vararg. This is a language restriction, and it’s specifically made so that calls remain unambiguous.

Mistake #4: using vararg “just in case”, even though there are always exactly two arguments.
vararg is a powerful tool, but if by meaning the function always has two values (for example, width and height), then vararg hurts readability: the call starts to look like the number of values can be anything, even though it can’t. At the API level this is misleading, so it’s better to keep normal parameters when the count is fixed.

Mistake #5: turning vararg into a way to “hide bad design”.
Sometimes you see an approach like “let’s pass everything as vararg and figure it out inside”. This is almost always bad: the function becomes unpredictable, and errors show up later. vararg is good when the set is homogeneous and logical (messages, numbers, strings with one meaning), not when it’s a grab bag of unrelated stuff.

Mistake #6: doing too much printing via say(vararg lines) and losing the program structure.
say(vararg lines: String) is useful, but if you start printing “everything under the sun” through it, it’s easy to lose track of where your logic is and where your UI is. A good rule of thumb: vararg functions usually do one small job (printing, counting, simple batch processing) and do not replace your program architecture.

1
Task
Kotlin SELF, level 16, lesson 0
Locked
Checkout on the Go
Checkout on the Go
1
Task
Kotlin SELF, level 16, lesson 0
Locked
Welcoming guests
Welcoming guests
1
Task
Kotlin SELF, level 16, lesson 0
Locked
Notes report
Notes report
1
Task
Kotlin SELF, level 16, lesson 0
Locked
Service debugging
Service debugging
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION