CodeGym /Courses /Kotlin SELF /Spread *: pass arrays into vararg without errors

Spread *: pass arrays into vararg without errors

Kotlin SELF
Level 16, Lesson 2
Available

1. Why you need spread *

When you write vararg, calling the function looks nice: sumAll(1, 2, 3). But real life likes to throw situations at you where the numbers (or strings) are already in an array. For example, you collected a “tail” of parameters, read them from input, or stored results from several game rounds. And then the classic beginner question appears: “why can’t I just pass an array?”

Let’s put into words what’s happening. vararg is a call form where you pass 0..N separate arguments. An array, on the other hand, is a single object (one variable) that contains N elements. And the compiler honestly treats the array as one argument, not as a “container that should be expanded.”

A visual diagram (simplified):

flowchart LR
    A["vararg expects: a, b, c (multiple arguments)"] --> B["call f(1, 2, 3)"]
    C["you have: arr = [1, 2, 3] (one variable)"] --> D["call f(arr) — that is one argument"]
    E["spread: *arr"] --> F["call f(*arr) — that is f(1, 2, 3)"]

In Kotlin, the spread operator * exists to solve this problem: it tells the compiler, “take the array elements and pass them as separate arguments.”

2. Spread for Array<T>

Let’s start with the friendliest case: a regular Array<String> or Array<Int>, i.e., an “object” array. It’s created with arrayOf(...). With this kind of array, spread reads as naturally as possible: f(*arr).

Minimal example: printing strings

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

fun main() {
    val tail: Array<String> = arrayOf("two", "three")
    printLines("one", *tail)
    // one
    // two
    // three
}

Pay attention to an important detail: *tail can be used only in an argument position in a function call. This is not an “operation on an array,” it is call-site syntax.

A bad call (and why it’s bad)

If you try to do this (I’ll leave it as a comment so your project still compiles):

fun main() {
    val tail = arrayOf("two", "three")

    printLines("one", tail)
    // Compilation error: tail is one argument of type Array<String>,
    // but the function expects String, String, String... (vararg)
}

The compiler won’t “guess” that you meant to “insert the array elements into the argument list.” For that, you must say it explicitly: *tail.

Mixed call: some arguments manually, some from an array

After you see f(*arr), the next practical scenario comes up almost immediately: “Can I specify a couple of values by hand and take the rest from the array?” Yes: you can pass normal arguments before and after the unpacking.

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

fun main() {
    val mid: Array<Int> = arrayOf(2, 3, 4)

    println(sumAll(1, *mid, 10)) // 20
}

The key idea here: *mid does not replace the entire argument list; it gets “spliced” into it.

If it feels like “inserting a stack of papers into the middle of a notebook” — yes, that analogy is pretty fair. Except the notebook doesn’t complain about types, while Kotlin does, and that’s actually helpful.

3. Primitive arrays and conversions

Now we get to the part where beginners start to suspect Kotlin is alive. The thing is, Kotlin has two families of arrays: Array<T> (for objects) and separate types for primitives: IntArray, DoubleArray, CharArray, etc. They exist so numbers are stored efficiently, without “boxing into objects.”

Practical consequence: not every array can be “unpacked” into every vararg. The array type must match the expected type of the vararg parameter.

vararg Int and IntArray: a good scenario

If your function is declared as fun sumAll(vararg xs: Int), then inside, xs is essentially an IntArray. And you can pass an IntArray into such a vararg via spread:

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

fun main() {
    val attempts: IntArray = intArrayOf(3, 5, 2)

    println(sumAll(*attempts)) // 10
}

This feels “logical”: IntArray contains Int, vararg xs: Int accepts Int.

IntArray is not Array<Int> (and sometimes that matters)

But Array<Int> is a different type. It’s created via arrayOf(1, 2, 3). And you can’t just put an equals sign between them, because they are genuinely different structures.

Practical takeaway: sometimes you’ll need a conversion to “move” from one array family to the other.

When you need toTypedArray()

Most often, “doesn’t compile” happens in this situation: you have an IntArray, but the function takes a vararg not of Int, but, for example, Any? (this is common for a “universal logger”) or some generic type. In that case, IntArray no longer fits, because it is not an Array<...>.

Example: the logger accepts Any?, but we have an IntArray

fun log(tag: String, vararg items: Any?) {
    print("[$tag] ")
    for (item in items) {
        print("$item ")
    }
    println()
}

fun main() {
    val attempts: IntArray = intArrayOf(3, 5, 2)

    val boxed: Array<Int> = attempts.toTypedArray()
    log("GAME", *boxed)
    // [GAME] 3 5 2
}

There are two steps here, and both matter:

1) attempts.toTypedArray() turns IntArray into Array<Int> (i.e., an “object” array).
2) *boxed unpacks Array<Int> into the vararg items.

Why can’t we just write log("GAME", *attempts)?

Because attempts is an IntArray, while vararg items: Any? inside the function is an Array<out Any?>. These types have a different nature. Kotlin can’t automatically “pretend” that IntArray is an array of objects: it has a different storage format.

In plain English: IntArray is a “box of digits,” while Array<Int> is a “box of little number-objects.” Spread can dump out the right kind of box, but the box has to match the expected shape.

Cheat sheet: what unpacks into what

What you have in a variable What the vararg expects What to write in the call
Array<String>
vararg String
f(*arr)
IntArray
vararg Int
f(*ints)
IntArray
vararg Any?
f(*ints.toTypedArray())

This table is not “for every case in life,” but at today’s level it covers 90% of practical situations.

4. Forwarding vararg into another vararg function

A common scenario appears when you build utilities. You wrote one handy function with vararg, and then you want to write another one that adds a “header,” “prefix,” “signature” — and calls the first one inside. And it’s easy to forget that inside the second function, vararg has already turned into an array, so to pass it further you need the *.

This follows directly from the definition: inside a function, a vararg parameter is used as an array.

Example: printing with a header

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

fun printWithHeader(header: String, vararg lines: String) {
    println(header)
    printLines(*lines) // important: *lines
}

fun main() {
    printWithHeader("== MENU ==", "Play", "Settings", "Exit")
    // == MENU ==
    // Play
    // Settings
    // Exit
}

If you remove *, you’ll be trying to pass Array<String> to a place where String, String, String... (vararg) are expected. That’s the same typical conflict, just “hidden” inside your own utility.

5. Example: stats for the “Guess the Number” game

So it doesn’t feel like spread exists only for abstract textbook examples, let’s embed it into a clear piece of a console app. We already built the “Guess the Number” game: it has rounds, attempts, and final messages. A logical next step is learning to print stats across multiple rounds nicely, without manually copying elements.

Let’s say we played several rounds and stored the number of attempts in an IntArray. Now we want to print them via a function that takes vararg Int.

Utility: printing attempt stats

fun printAttempts(vararg attempts: Int) {
    print("Attempts: ")
    for (a in attempts) print("$a ")
    println()
}

fun main() {
    val attemptsByRound: IntArray = intArrayOf(4, 2, 6)

    printAttempts(*attemptsByRound) // unpacked IntArray
    // Attempts: 4 2 6
}

The key point: you didn’t change printAttempts to “know about arrays.” It stays convenient for calls like printAttempts(3, 5, 1), but you can still “feed” it an array via *.

The same output, but with a universal logger

If you want a “single logging function for everything,” it often takes Any?, so you can pass strings, numbers, and null.

fun log(tag: String, vararg items: Any?) {
    print("[$tag] ")
    for (item in items) print("$item ")
    println()
}

fun main() {
    val attemptsByRound: IntArray = intArrayOf(4, 2, 6)

    log("GAME", *attemptsByRound.toTypedArray())
    // [GAME] 4 2 6
}

The toTypedArray() + * combo is like “repack your things into a suitcase of the right format, then unzip it.” It looks a bit longer, but it’s transparent in meaning.

6. Typical mistakes when working with spread * and vararg

Error #1: pass an array into a vararg without * and then wonder “why Kotlin is being picky.”
Usually it looks like this: printLines(linesArray) instead of printLines(*linesArray). The compiler is right here: you passed one argument of type Array<String>, while the function expects many arguments of type String. The habit “if you need vararg, remember *” saves a lot of time.

Error #2: try to use * outside of a function call.
The spread operator is not an “operation on an array,” not a “special loop,” and not “unpacking magic everywhere.” It works in one specific position: before the array name in a function’s argument list. If you try to apply * in a different context, you’ll get a syntax error — and that’s normal.

Error #3: mix up Array<Int> and IntArray and get stuck in conversions.
In practice, it looks like this: you have an IntArray, but you try to pass it where an Array<...> is expected (for example, vararg Any?), or the other way around. It’s useful to remember that primitive arrays are a separate “type line” and do not inherit from Array, even though they look similar. If the types don’t match, you either choose the correct array type when creating it, or you do an explicit conversion.

Error #4: forget * when forwarding vararg to another vararg function.
A very common bug in utilities: you write fun a(vararg xs: String), then fun b(vararg xs: String) { a(xs) } — and you hit a type error. The reason is simple: inside b, the parameter xs is already an array, and when passing it “as a set of arguments” you need to unpack it: a(*xs). This directly follows from the fact that vararg is used as an array inside the function.

Error #5: use toTypedArray() “on autopilot” without understanding why.
toTypedArray() is a useful tool, but it’s not always needed. If your function takes vararg Int, and you already have an IntArray, most of the time f(*ints) is enough. The conversion becomes necessary when you move between a “primitive” array and an “object” array, or when the vararg accepts a type like Any?.

1
Task
Kotlin SELF, level 16, lesson 2
Locked
Team greeting
Team greeting
1
Task
Kotlin SELF, level 16, lesson 2
Locked
Average grade
Average grade
1
Task
Kotlin SELF, level 16, lesson 2
Locked
Attempts log
Attempts log
1
Task
Kotlin SELF, level 16, lesson 2
Locked
Menu with header
Menu with header
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION