0
0
Kotlinprogramming~20 mins

Vararg parameters in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Vararg Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of function with vararg parameter
What is the output of this Kotlin code using a vararg parameter?
Kotlin
fun printAll(vararg messages: String) {
    for (m in messages) print("$m ")
}

fun main() {
    printAll("Hi", "there", "Kotlin")
}
A[Hi, there, Kotlin]
BHi,there,Kotlin
C
Hi
there
Kotlin
DHi there Kotlin
Attempts:
2 left
💡 Hint
Remember that the function prints each message followed by a space.
🧠 Conceptual
intermediate
1:30remaining
Vararg parameter usage in Kotlin
Which statement about vararg parameters in Kotlin is true?
AVararg parameters must always be the first parameter in the function.
BA function can have multiple vararg parameters.
CVararg parameters allow passing zero or more arguments of the specified type.
DYou cannot pass an array to a vararg parameter.
Attempts:
2 left
💡 Hint
Think about how many arguments you can pass to a vararg parameter.
Predict Output
advanced
2:00remaining
Output with vararg and spread operator
What is the output of this Kotlin code snippet?
Kotlin
fun sumAll(vararg numbers: Int): Int {
    var sum = 0
    for (n in numbers) sum += n
    return sum
}

fun main() {
    val nums = intArrayOf(1, 2, 3)
    println(sumAll(*nums, 4))
}
ACompilation error
B10
C7
D6
Attempts:
2 left
💡 Hint
The spread operator (*) passes array elements as individual arguments.
🔧 Debug
advanced
2:00remaining
Identify the error with vararg usage
What error does this Kotlin code produce?
Kotlin
fun printNumbers(prefix: String, vararg nums: Int) {
    for (n in nums) print("$prefix$n ")
}

fun main() {
    printNumbers(prefix = "#", 1, 2, 3)
}
APrints: #1 #2 #3
BRuntime error: prefix not found
CCompilation error: missing argument for prefix
DCompilation error: vararg parameter must be the last parameter
Attempts:
2 left
💡 Hint
Check the order of parameters when using vararg.
🚀 Application
expert
2:30remaining
Count total characters using vararg strings
What is the value of totalChars after running this Kotlin code?
Kotlin
fun countChars(vararg words: String): Int {
    return words.sumOf { it.length }
}

fun main() {
    val totalChars = countChars("Kotlin", "is", "fun")
}
A11
B10
C12
DCompilation error
Attempts:
2 left
💡 Hint
Add the lengths of all strings passed as arguments.