0
0
Kotlinprogramming~20 mins

Function references (::functionName) in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Function Reference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
ACompilation error
B[1, 2, 3, 4]
C[2, 4, 6, 8]
D[1, 4, 9, 16]
Attempts:
2 left
💡 Hint
Remember that ::square passes the function itself to map, which applies it to each element.
Predict Output
intermediate
2: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"))
}
AHello, greetFunction!
BCompilation error
CHello, Alice!
DgreetFunction
Attempts:
2 left
💡 Hint
Bound function references keep the instance context.
🔧 Debug
advanced
2: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)
}
AType mismatch: Expected a function of type (Int) -> R but found (Int, Int) -> Int
BCompilation error: Unresolved reference 'add'
C[2, 3, 4]
D[1, 2, 3]
Attempts:
2 left
💡 Hint
Check the expected function type for map and the signature of add.
Predict Output
advanced
2: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)
}
A[2, 4, 6]
B[1, 3, 5]
C[1, 2, 3, 4, 5, 6]
DCompilation error
Attempts:
2 left
💡 Hint
filter uses the function reference as a predicate to select elements.
Predict Output
expert
2: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)
}
ARuntime error
BCompilation error: Overload resolution ambiguity
CString: 42
DInt: 42
Attempts:
2 left
💡 Hint
Consider how Kotlin resolves overloaded function references with a general type.