0
0
Kotlinprogramming~5 mins

Vararg parameters in Kotlin

Choose your learning style9 modes available
Introduction

Vararg parameters let you send many values to a function without making a list first. It makes your code simpler and easier to use.

When you want to add many numbers together without creating a list first.
When you want to print many messages with one function call.
When you want to pass a flexible number of items to a function, like names or scores.
When you want to collect many inputs but don't know how many there will be.
When you want to combine several strings or values quickly.
Syntax
Kotlin
fun functionName(vararg parameterName: Type) {
    // function body
}

You can only have one vararg parameter in a function.

If there are other parameters, vararg should usually be last.

Examples
This function prints all strings passed to it.
Kotlin
fun printAll(vararg messages: String) {
    for (m in messages) println(m)
}
This function adds all numbers given and returns the total.
Kotlin
fun sumAll(vararg numbers: Int): Int {
    var sum = 0
    for (n in numbers) sum += n
    return sum
}
This function greets each name with the given greeting.
Kotlin
fun greet(greeting: String, vararg names: String) {
    for (name in names) println("$greeting, $name!")
}
Sample Program

This program defines a function that prints all numbers passed to it. The main function calls it with four numbers.

Kotlin
fun printNumbers(vararg nums: Int) {
    for (num in nums) {
        println(num)
    }
}

fun main() {
    printNumbers(5, 10, 15, 20)
}
OutputSuccess
Important Notes

You can pass an array to a vararg parameter using the spread operator (*), like printNumbers(*myArray).

Vararg parameters are useful when you want to keep your function calls simple and flexible.

Summary

Vararg lets you send many values to a function without making a list first.

Only one vararg parameter is allowed per function, usually last.

Use vararg to make your functions easier to call with many inputs.