0
0
Kotlinprogramming~20 mins

Infix functions for readable calls in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Infix Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
AHiHiHi
BHi 3 times
C3Hi
DError: infix function cannot be called like this
Attempts:
2 left
💡 Hint
Remember infix functions allow calling like 'a times b' instead of 'a.times(b)'.
Predict Output
intermediate
2: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)
}
AHello World!!!
BError: cannot chain infix functions without parentheses
CHello World exclaim 3
DHello World!3
Attempts:
2 left
💡 Hint
Infix functions can be chained if the return type matches the next function's receiver.
🔧 Debug
advanced
2: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)
}
ATypeError: Cannot add Int and Unit
BSyntaxError: Missing argument for infix function
CCompilation error: Infix function call must have exactly one argument
DNo error, prints 5
Attempts:
2 left
💡 Hint
Infix functions require exactly one argument when called.
🧠 Conceptual
advanced
2:00remaining
Understanding infix function constraints
Which of the following is NOT a requirement for defining an infix function in Kotlin?
AIt must have exactly one parameter
BIt must return Unit (void)
CIt must be marked with the 'infix' keyword
DIt must be a member function or an extension function
Attempts:
2 left
💡 Hint
Think about what return types infix functions can have.
Predict Output
expert
2: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")
}
ACompilation error: infix function cannot have nullable receiver
B
null
Kotlin
C
Default
Default
D
Default
Kotlin
Attempts:
2 left
💡 Hint
The Elvis operator ?: returns the left side if not null, otherwise the right side.