Bird
Raised Fist0
Kotlinprogramming~10 mins

Vararg parameters in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Vararg parameters
Function call with multiple arguments
↓
Vararg parameter collects all arguments
↓
Function processes each argument
↓
Function returns or prints result
↓
End
The function receives multiple arguments as a single vararg parameter, processes each one, and then finishes.
Execution Sample
Kotlin
fun printAll(vararg messages: String) {
    for (m in messages) {
        println(m)
    }
}

printAll("Hi", "Hello", "Hey")
This code defines a function that takes any number of strings and prints each one.
Execution Table
StepActionVariable 'messages'Loop Variable 'm'Output
1Function called with arguments "Hi", "Hello", "Hey"["Hi", "Hello", "Hey"]
2Start loop over 'messages'["Hi", "Hello", "Hey"]HiHi
3Next loop iteration["Hi", "Hello", "Hey"]HelloHello
4Next loop iteration["Hi", "Hello", "Hey"]HeyHey
5Loop ends, function returns["Hi", "Hello", "Hey"]
💡 All elements in 'messages' processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
messagesempty["Hi", "Hello", "Hey"]["Hi", "Hello", "Hey"]["Hi", "Hello", "Hey"]["Hi", "Hello", "Hey"]
mundefinedHiHelloHeyundefined
Key Moments - 3 Insights
Why does 'messages' hold all arguments as an array?
Because 'vararg' collects all passed arguments into a single array, as shown in execution_table step 1.
What happens if no arguments are passed to the vararg parameter?
The 'messages' array is empty, so the loop does not run, and no output is produced (not shown here but implied).
Can we pass an existing array to a vararg parameter?
Yes, but we must use the spread operator (*) to pass the array elements individually.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'm' at step 3?
AHi
BHey
CHello
Dmessages array
💡 Hint
Check the 'Loop Variable m' column at step 3 in the execution_table.
At which step does the loop finish processing all arguments?
AStep 5
BStep 3
CStep 2
DStep 4
💡 Hint
Look for the step where the loop ends in the execution_table.
If we call printAll() with no arguments, what changes in the execution?
AThe loop runs once with an empty string
BThe 'messages' array is empty and loop does not run
CThe function throws an error
DThe function prints 'null'
💡 Hint
Refer to key_moments about empty vararg behavior.
Concept Snapshot
fun functionName(vararg paramName: Type) {
  // paramName is an array of Type
}

- Use 'vararg' to accept any number of arguments
- Inside function, paramName behaves like an array
- Call function with multiple values or spread an array
- Useful for flexible argument counts
Full Transcript
This visual execution shows how Kotlin's vararg parameter works. When the function printAll is called with three strings, these are collected into the 'messages' array. The function loops over each element, printing them one by one. The variable 'm' takes each string in turn. The loop ends after all elements are processed. If no arguments are passed, the array is empty and the loop does not run. Passing an existing array requires the spread operator. This helps functions accept flexible numbers of arguments easily.

Practice

(1/5)
1.

What does the vararg keyword do in Kotlin functions?

easy
A. Allows passing a variable number of arguments to a function
B. Declares a function that returns multiple values
C. Defines a function with no parameters
D. Specifies a function that accepts only one argument

Solution

  1. Step 1: Understand the purpose of vararg

    The vararg keyword lets a function accept zero or more arguments of the same type without needing an array or list explicitly.
  2. Step 2: Compare options with this meaning

    Only Allows passing a variable number of arguments to a function correctly describes this behavior, while others describe unrelated function features.
  3. Final Answer:

    Allows passing a variable number of arguments to a function -> Option A
  4. Quick Check:

    Vararg = variable arguments [OK]
Hint: Vararg means many arguments, not just one [OK]
Common Mistakes:
  • Thinking vararg returns multiple values
  • Confusing vararg with no parameters
  • Assuming vararg limits to one argument
2.

Which of the following is the correct syntax to declare a function with a vararg parameter in Kotlin?

fun printAll(____ numbers: Int) { for (n in numbers) println(n) }
easy
A. var
B. varargs
C. vararg
D. args

Solution

  1. Step 1: Recall the exact keyword for variable arguments

    Kotlin uses vararg (singular) to declare variable number of arguments.
  2. Step 2: Check each option

    Only vararg matches the correct keyword; others are incorrect or invalid syntax.
  3. Final Answer:

    vararg -> Option C
  4. Quick Check:

    Keyword is vararg, not varargs [OK]
Hint: Remember: vararg is singular keyword [OK]
Common Mistakes:
  • Using 'varargs' instead of 'vararg'
  • Omitting the keyword entirely
  • Using 'var' or 'args' which are invalid here
3.

What is the output of this Kotlin code?

fun sumAll(vararg numbers: Int): Int { var sum = 0; for (n in numbers) sum += n; return sum }

fun main() {
  println(sumAll(1, 2, 3))
  println(sumAll())
}
medium
A. Error and error
B. 6 and error
C. Error and 0
D. 6 and 0

Solution

  1. Step 1: Understand the function behavior with vararg

    The function sums all integers passed. If no arguments, the loop does not run, sum stays 0.
  2. Step 2: Calculate outputs for calls

    sumAll(1,2,3) = 1+2+3 = 6; sumAll() = 0 (no arguments)
  3. Final Answer:

    6 and 0 -> Option D
  4. Quick Check:

    Sum of inputs or zero if none [OK]
Hint: Vararg can be empty, sum then zero [OK]
Common Mistakes:
  • Assuming empty vararg causes error
  • Forgetting sum starts at zero
  • Confusing vararg with list requiring explicit array
4.

Identify the error in this Kotlin function declaration:

fun printNames(vararg names: String, age: Int) {
  for (name in names) println(name)
  println(age)
}
medium
A. Function cannot have more than one parameter
B. Vararg parameter must be the last parameter
C. Vararg parameter cannot be of type String
D. Vararg parameters must be declared with 'varargs'

Solution

  1. Step 1: Recall vararg parameter position rule

    Kotlin requires the vararg parameter to be the last in the parameter list.
  2. Step 2: Check the function parameters

    Here, vararg names is before age, which is invalid syntax.
  3. Final Answer:

    Vararg parameter must be the last parameter -> Option B
  4. Quick Check:

    Vararg last parameter rule [OK]
Hint: Vararg must always be last parameter [OK]
Common Mistakes:
  • Placing vararg parameter before others
  • Thinking vararg can be anywhere
  • Using 'varargs' instead of 'vararg'
5.

Given this function:

fun combine(vararg parts: String): String {
  return parts.joinToString(separator = ", ")
}

Which call correctly passes an existing array val arr = arrayOf("a", "b", "c") to combine?

hard
A. combine(*arr)
B. combine(arr)
C. combine(arr.toList())
D. combine(arr as String)

Solution

  1. Step 1: Understand how to pass an array to vararg

    Kotlin requires the spread operator * to pass an array as vararg arguments.
  2. Step 2: Evaluate each option

    combine(*arr) uses *arr, correctly spreading the array. combine(arr) passes the array as a single argument, not vararg. combine(arr.toList()) passes a list, not vararg. combine(arr as String) is invalid cast.
  3. Final Answer:

    combine(*arr) -> Option A
  4. Quick Check:

    Use * to spread array for vararg [OK]
Hint: Use * to spread array into vararg [OK]
Common Mistakes:
  • Passing array without * operator
  • Passing list instead of array
  • Trying invalid casts to String
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard