Challenge - 5 Problems
Infix Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of infix function call
What is the output of this Kotlin code using an infix function?
Kotlin
infix fun Int.times(str: String) = str.repeat(this) fun main() { val result = 3 times "Hi" println(result) }
Attempts:
2 left
💡 Hint
Remember infix functions allow calling like 'a times b' instead of 'a.times(b)'.
✗ Incorrect
The infix function 'times' repeats the string the number of times specified by the integer. So 3 times "Hi" produces "HiHiHi".
❓ Predict Output
intermediate2:00remaining
Result of chained infix calls
What is the output of this Kotlin code with chained infix calls?
Kotlin
infix fun String.append(s: String) = this + s infix fun String.exclaim(times: Int) = this + "!".repeat(times) fun main() { val result = "Hello" append " World" exclaim 3 println(result) }
Attempts:
2 left
💡 Hint
Infix functions can be chained if the return type matches the next function's receiver.
✗ Incorrect
The first infix call appends " World" to "Hello", then the second adds three exclamation marks, resulting in "Hello World!!!".
🔧 Debug
advanced2:00remaining
Identify the error in infix function usage
What error does this Kotlin code produce?
Kotlin
infix fun Int.add(other: Int) = this + other fun main() { val sum = 5 add println(sum) }
Attempts:
2 left
💡 Hint
Infix functions require exactly one argument when called.
✗ Incorrect
The call '5 add' is missing the argument for the infix function 'add', causing a compilation error.
🧠 Conceptual
advanced2:00remaining
Understanding infix function constraints
Which of the following is NOT a requirement for defining an infix function in Kotlin?
Attempts:
2 left
💡 Hint
Think about what return types infix functions can have.
✗ Incorrect
Infix functions can return any type, not just Unit. The other options are required.
❓ Predict Output
expert2:00remaining
Output of infix function with nullable receiver
What is the output of this Kotlin code?
Kotlin
infix fun String?.orDefault(default: String) = this ?: default fun main() { val a: String? = null val b: String? = "Kotlin" println(a orDefault "Default") println(b orDefault "Default") }
Attempts:
2 left
💡 Hint
The Elvis operator ?: returns the left side if not null, otherwise the right side.
✗ Incorrect
For 'a' which is null, the default is returned. For 'b' which is "Kotlin", it returns 'b'.