Kotlin Kotlin Functions and Lambdas 2 — Questions and Answers
Question 1: What is the type of a lambda that takes an Int and returns a String in Kotlin?
- Lambda<Int, String>
- (Int) -> String (Correct answer)
- Function<Int, String>
- Int => String
Correct answer: (Int) -> String
Kotlin function types use the `(ParameterTypes) -> ReturnType` syntax, so an Int-to-String lambda is `(Int) -> String`.
Question 2: What does the `crossinline` modifier do on a lambda parameter?
- Prevents the lambda from being inlined
- Prevents non-local returns inside the lambda (Correct answer)
- Forces the lambda to run on a separate thread
- Makes the lambda nullable
Correct answer: Prevents non-local returns inside the lambda
`crossinline` prevents non-local returns inside a lambda that is called from a different execution context while still allowing inlining.
Question 3: How do you reference an existing function as a value in Kotlin?
- Using the `ref` keyword
- Using the `::` operator (Correct answer)
- Using the `&` operator
- Wrapping it in a lambda explicitly
Correct answer: Using the `::` operator
The `::` operator creates a function reference, allowing an existing function to be treated as a first-class value.
Question 4: Which built-in higher-order function applies a transformation to each element of a collection?
- filter
- reduce
- map (Correct answer)
- fold
Correct answer: map
`map` applies a given transformation function to each element of a collection and returns a new list of results.
Question 5: What does `noinline` do on an inline function parameter?
- Forces the lambda to be inlined
- Prevents that specific lambda parameter from being inlined (Correct answer)
- Makes the lambda run asynchronously
- Marks the parameter as optional
Correct answer: Prevents that specific lambda parameter from being inlined
`noinline` disables inlining for a specific lambda parameter of an `inline` function, useful when you need to store or return the lambda.
Question 6: What is the difference between `fun` and a lambda in Kotlin?
- Lambdas cannot have return types
- `fun` requires explicit return, lambdas return the last expression (Correct answer)
- Lambdas cannot capture outer variables
- `fun` is always anonymous, lambdas always have names
Correct answer: `fun` requires explicit return, lambdas return the last expression
Named functions declared with `fun` use explicit `return`, while lambdas automatically return the value of their last expression.
What is the type of a lambda that takes an Int and returns a String in Kotlin?