Kotlin Kotlin Functions and Lambdas 1 — Questions and Answers
Question 1: What is a higher-order function in Kotlin?
- A function with more than 5 parameters
- A function that takes or returns another function (Correct answer)
- A function defined inside a class
- A function marked with the `high` keyword
Correct answer: A function that takes or returns another function
A higher-order function is one that accepts functions as parameters or returns a function as its result.
Question 2: What does the `it` keyword represent inside a Kotlin lambda?
- The return type of the lambda
- The implicit single parameter of the lambda (Correct answer)
- The enclosing class instance
- The last expression result
Correct answer: The implicit single parameter of the lambda
When a lambda has exactly one parameter, Kotlin allows omitting the parameter declaration and referring to it as `it`.
Question 3: Which Kotlin keyword is used to mark a function as inline?
- inlined
- inline (Correct answer)
- @Inline
- embed
Correct answer: inline
The `inline` modifier tells the Kotlin compiler to substitute the function body at the call site, reducing lambda overhead.
Question 4: What is a lambda expression in Kotlin?
- A named function stored in a variable
- An anonymous function defined with curly braces (Correct answer)
- A function inside an object declaration
- A recursive function
Correct answer: An anonymous function defined with curly braces
A lambda in Kotlin is an anonymous function literal enclosed in curly braces, which can be passed as a value.
Question 5: How do you pass a trailing lambda in Kotlin?
- Place it inside parentheses after the function name
- Place it outside the parentheses after the function call (Correct answer)
- Use the `lambda` keyword before the block
- Lambdas cannot be trailing in Kotlin
Correct answer: Place it outside the parentheses after the function call
Kotlin allows moving the last lambda argument outside the parentheses, a convention called trailing lambda syntax.
Question 6: What does the `return@label` syntax do in Kotlin?
- Returns from the enclosing function
- Returns from a specific lambda or function using a label (Correct answer)
- Throws an exception
- Restarts the enclosing loop
Correct answer: Returns from a specific lambda or function using a label
Labeled returns (`return@label`) allow returning from a specific lambda or function scope rather than the enclosing function.
What is a higher-order function in Kotlin?