Challenge - 5 Problems
Function Reference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of function reference with map
What is the output of this Kotlin code using function references?
Kotlin
fun square(x: Int) = x * x fun main() { val numbers = listOf(1, 2, 3, 4) val squares = numbers.map(::square) println(squares) }
Attempts:
2 left
💡 Hint
Remember that ::square passes the function itself to map, which applies it to each element.
✗ Incorrect
The function reference ::square is passed to map, which calls square on each number, producing their squares.
❓ Predict Output
intermediate2:00remaining
Using bound function reference
What will this Kotlin code print?
Kotlin
class Greeter(val greeting: String) { fun greet(name: String) = "$greeting, $name!" } fun main() { val greeter = Greeter("Hello") val greetFunction = greeter::greet println(greetFunction("Alice")) }
Attempts:
2 left
💡 Hint
Bound function references keep the instance context.
✗ Incorrect
The bound reference greeter::greet keeps the greeter instance, so calling greetFunction("Alice") returns "Hello, Alice!".
🔧 Debug
advanced2:00remaining
Identify the error with function reference usage
What error does this Kotlin code produce?
Kotlin
fun add(a: Int, b: Int) = a + b fun main() { val numbers = listOf(1, 2, 3) val result = numbers.map(::add) println(result) }
Attempts:
2 left
💡 Hint
Check the expected function type for map and the signature of add.
✗ Incorrect
map expects a function taking one argument, but add takes two, causing a type mismatch error.
❓ Predict Output
advanced2:00remaining
Using function reference with filter and predicate
What is the output of this Kotlin code?
Kotlin
fun isEven(n: Int) = n % 2 == 0 fun main() { val numbers = listOf(1, 2, 3, 4, 5, 6) val evens = numbers.filter(::isEven) println(evens) }
Attempts:
2 left
💡 Hint
filter uses the function reference as a predicate to select elements.
✗ Incorrect
The function reference ::isEven is used as a predicate to filter even numbers from the list.
❓ Predict Output
expert2:00remaining
Output of function reference with overloaded functions
What will this Kotlin code print?
Kotlin
fun printValue(value: Int) = println("Int: $value") fun printValue(value: String) = println("String: $value") fun main() { val printer: (Any) -> Unit = ::printValue printer(42) }
Attempts:
2 left
💡 Hint
Consider how Kotlin resolves overloaded function references with a general type.
✗ Incorrect
The compiler cannot decide which printValue to use for (Any) -> Unit, causing an overload resolution ambiguity error.