Challenge - 5 Problems
Single-expression Kotlin Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of a single-expression function with string interpolation
What is the output of this Kotlin code?
Kotlin
fun greet(name: String) = "Hello, $name!" fun main() { println(greet("Anna")) }
Attempts:
2 left
💡 Hint
Look at how the function returns a string using $name inside quotes.
✗ Incorrect
The function greet is a single-expression function that returns the string "Hello, " concatenated with the value of name and an exclamation mark. When called with "Anna", it prints "Hello, Anna!".
❓ Predict Output
intermediate1:30remaining
Return type inference in single-expression functions
What will this Kotlin program print?
Kotlin
fun square(x: Int) = x * x fun main() { println(square(5)) }
Attempts:
2 left
💡 Hint
The function returns the product of x times x.
✗ Incorrect
The function square returns the square of the input number. For input 5, it returns 25.
🔧 Debug
advanced2:00remaining
Identify the error in this single-expression function
What error does this Kotlin code produce?
Kotlin
fun add(a: Int, b: Int) = return a + b fun main() { println(add(3, 4)) }
Attempts:
2 left
💡 Hint
Single-expression functions do not use the 'return' keyword explicitly.
✗ Incorrect
In Kotlin, single-expression functions automatically return the expression value. Using 'return' explicitly causes a syntax error.
❓ Predict Output
advanced1:30remaining
Output of a single-expression function with conditional expression
What is the output of this Kotlin code?
Kotlin
fun max(a: Int, b: Int) = if (a > b) a else b fun main() { println(max(10, 20)) }
Attempts:
2 left
💡 Hint
The function returns the greater of two numbers using if-else.
✗ Incorrect
The function max returns the larger of a and b. For inputs 10 and 20, it returns 20.
🧠 Conceptual
expert2:00remaining
Understanding single-expression function behavior with side effects
Consider this Kotlin code. What is the output when main() runs?
Kotlin
var counter = 0 fun increment() = counter++ fun main() { println(increment()) println(increment()) }
Attempts:
2 left
💡 Hint
The post-increment operator returns the value before incrementing.
✗ Incorrect
The function increment returns the current value of counter, then increases it by 1. So the first call prints 0, the second prints 1.