0
0
Kotlinprogramming~20 mins

Why functions are first-class in Kotlin - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Functions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using a function variable?

Look at this Kotlin code where a function is stored in a variable and then called. What will it print?

Kotlin
val greet: (String) -> String = { name -> "Hello, $name!" }
println(greet("Alice"))
ACompilation error
Bgreet
CHello, name!
DHello, Alice!
Attempts:
2 left
💡 Hint

Think about how the lambda uses the parameter and how the variable is called like a function.

🧠 Conceptual
intermediate
1:30remaining
Why can Kotlin functions be passed as arguments?

Why can Kotlin functions be passed as arguments to other functions?

ABecause Kotlin automatically converts functions to strings when passed.
BBecause functions are treated as objects and can be stored in variables or passed around.
CBecause Kotlin does not allow functions as arguments, only variables.
DBecause functions are compiled into separate files.
Attempts:
2 left
💡 Hint

Think about what it means for functions to be 'first-class'.

🔧 Debug
advanced
2:30remaining
What error does this Kotlin code raise?

What error will this Kotlin code produce?

Kotlin
fun applyOperation(x: Int, y: Int, op: (Int, Int) -> Int): Int {
    return op(x, y)
}

val result = applyOperation(5, 3, { a, b -> a + b + c })
println(result)
ANo error, prints 8
BType mismatch error
CUnresolved reference: c
DNull pointer exception
Attempts:
2 left
💡 Hint

Check the lambda parameters and variables used inside it.

Predict Output
advanced
2:00remaining
What is the output of this Kotlin higher-order function?

What will this Kotlin code print?

Kotlin
fun operateOnList(numbers: List<Int>, operation: (Int) -> Int): List<Int> {
    return numbers.map(operation)
}

val doubled = operateOnList(listOf(1, 2, 3)) { it * 2 }
println(doubled)
A[2, 4, 6]
B[1, 2, 3]
C[3, 6, 9]
DCompilation error
Attempts:
2 left
💡 Hint

Think about what map does with the lambda.

🧠 Conceptual
expert
3:00remaining
Why are functions considered first-class citizens in Kotlin?

Choose the best explanation why Kotlin treats functions as first-class citizens.

ABecause functions can be assigned to variables, passed as parameters, and returned from other functions.
BBecause functions in Kotlin cannot be overloaded or overridden.
CBecause Kotlin compiles functions into separate JVM classes automatically.
DBecause functions must always be declared inside classes.
Attempts:
2 left
💡 Hint

Recall what 'first-class' means in programming languages.