← Back to Kotlin Course | Chapter 8: Collections | Lesson 7 of 7

Spread Operator

The spread operator lets you pour every item out of an existing array straight into a function call that expects them one by one.

Declaring a vararg Function

A parameter marked vararg accepts any number of individual arguments of that type, which are made available inside the function as an array.

Example: Declaring a vararg Function

markup
fun sumAll(vararg numbers: Int): Int {
    return numbers.sum()
}

fun main() {
    println("Sum: ${sumAll(1, 2, 3, 4)}")
}

Spreading an Array into vararg

When you already have an array and want to pass its contents as individual arguments to a vararg parameter, prefix it with * -- this is the spread operator.

Example: Spreading an Array into vararg

markup
fun sumAll(vararg numbers: Int): Int {
    return numbers.sum()
}

fun main() {
    val values = intArrayOf(10, 20, 30)
    println("Sum: ${sumAll(*values)}")
}

Spreading a List

Since the spread operator works on arrays, a List must first be converted with .toTypedArray() before it can be spread into a vararg parameter.

Example: Spreading a List

markup
fun joinAll(vararg words: String): String {
    return words.joinToString(" ")
}

fun main() {
    val wordList = listOf("Hello", "from", "Kotlin")
    println(joinAll(*wordList.toTypedArray()))
}

Combining Spread with Other Arguments

A spread array can be mixed with additional individual arguments in the same call, as long as the overall argument order still matches how the function expects them.

Example: Combining Spread with Other Arguments

markup
fun sumAll(vararg numbers: Int): Int {
    return numbers.sum()
}

fun main() {
    val values = intArrayOf(1, 2, 3)
    println("Sum: ${sumAll(0, *values, 100)}")
}
Common Mistakes
  1. Forgetting the * prefix when passing an array to a vararg parameter, causing a type mismatch since a single array is not the same as several individual arguments.
  2. Trying to spread a List directly; the spread operator works on arrays, so a List must be converted with .toTypedArray() first.
  3. Assuming spread can mix with other individual arguments incorrectly ordered; extra positional arguments before/after a spread must still respect parameter order rules.
Chapter Summary
  • The * (spread) operator unpacks an array into individual arguments for a vararg parameter.
  • Without *, passing an array directly to a vararg parameter is a type mismatch.
  • A List must first be converted to an array with .toTypedArray() before it can be spread.
  • Spread arguments can be combined with additional individual arguments in the same call.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.