Challenge - 5 Problems
Vararg Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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") }
Attempts:
2 left
💡 Hint
Remember that the function prints each message followed by a space.
✗ Incorrect
The function loops through each string in the vararg and prints it with a trailing space, so the output is all words separated by spaces on the same line.
🧠 Conceptual
intermediate1:30remaining
Vararg parameter usage in Kotlin
Which statement about vararg parameters in Kotlin is true?
Attempts:
2 left
💡 Hint
Think about how many arguments you can pass to a vararg parameter.
✗ Incorrect
Vararg parameters let you pass zero or more arguments of the specified type. Only one vararg parameter is allowed per function, and it must be the last parameter. You can pass an array using the spread operator.
❓ Predict Output
advanced2: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)) }
Attempts:
2 left
💡 Hint
The spread operator (*) passes array elements as individual arguments.
✗ Incorrect
The array nums contains 1, 2, 3. Using *nums passes these as separate arguments along with 4, so sumAll sums 1+2+3+4 = 10.
🔧 Debug
advanced2: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) }
Attempts:
2 left
💡 Hint
Check the order of parameters when using vararg.
✗ Incorrect
In Kotlin, the vararg parameter must be the last parameter in the function declaration. Here, prefix comes before vararg, which is correct, so the code compiles and prints the output.
🚀 Application
expert2: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") }
Attempts:
2 left
💡 Hint
Add the lengths of all strings passed as arguments.
✗ Incorrect
The strings are "Kotlin" (6 letters), "is" (2 letters), and "fun" (3 letters). Total is 6 + 2 + 3 = 11.