Look at this Kotlin code where a function is stored in a variable and then called. What will it print?
val greet: (String) -> String = { name -> "Hello, $name!" } println(greet("Alice"))
Think about how the lambda uses the parameter and how the variable is called like a function.
The variable greet holds a function that takes a String and returns a greeting. Calling greet("Alice") runs the function and returns "Hello, Alice!" which is printed.
Why can Kotlin functions be passed as arguments to other functions?
Think about what it means for functions to be 'first-class'.
Kotlin treats functions as first-class citizens, meaning they can be stored in variables, passed as arguments, and returned from other functions just like any other object.
What error will this Kotlin code produce?
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)
Check the lambda parameters and variables used inside it.
The lambda uses a variable c which is not defined anywhere, causing an 'Unresolved reference: c' error.
What will this Kotlin code print?
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)
Think about what map does with the lambda.
The operateOnList function applies the lambda { it * 2 } to each element, doubling each number. So the output list is [2, 4, 6].
Choose the best explanation why Kotlin treats functions as first-class citizens.
Recall what 'first-class' means in programming languages.
First-class functions means they can be treated like any other value: stored, passed, and returned. Kotlin supports this fully.