Kotlin Kotlin Functional Programming 1 — Questions and Answers
Question 1: What is a lambda expression in Kotlin?
- A named function
- An anonymous function literal that can be stored in a variable or passed as an argument (Correct answer)
- A class with a single method
- A type alias
Correct answer: An anonymous function literal that can be stored in a variable or passed as an argument
A lambda in Kotlin is an anonymous function literal enclosed in `{}` that can be passed as a value or stored in a variable.
Question 2: What does `it` refer to inside a Kotlin lambda?
- The outer class instance
- The implicit single parameter of the lambda (Correct answer)
- The last expression value
- The return type
Correct answer: The implicit single parameter of the lambda
When a lambda has exactly one parameter, Kotlin allows you to omit the parameter declaration and refer to it as `it`.
Question 3: What is a higher-order function in Kotlin?
- A function with more than 3 parameters
- A function that takes functions as parameters or returns a function (Correct answer)
- A recursive function
- A function defined inside a class
Correct answer: A function that takes functions as parameters or returns a function
A higher-order function in Kotlin takes one or more functions as arguments or returns a function as its result.
Question 4: What is function composition in Kotlin?
- Calling multiple functions in sequence
- Combining two functions into a new function where one's output is the other's input (Correct answer)
- Defining a function inside another function
- Overloading functions
Correct answer: Combining two functions into a new function where one's output is the other's input
Function composition creates a new function by chaining two functions so the output of the first becomes the input of the second.
Question 5: What does the `let` scope function do in Kotlin?
- Declares a block of code
- Calls a lambda with the object as its argument and returns the lambda result (Correct answer)
- Modifies the object in place
- Creates a copy of the object
Correct answer: Calls a lambda with the object as its argument and returns the lambda result
`let` calls the lambda block with the receiver object as the argument (`it`) and returns the result of the lambda.
Question 6: What is a closure in Kotlin?
- A sealed class
- A lambda that captures variables from its surrounding scope (Correct answer)
- A function that closes a stream
- A private inner class
Correct answer: A lambda that captures variables from its surrounding scope
A closure is a lambda or anonymous function that captures and retains access to variables from its enclosing scope.
What is a lambda expression in Kotlin?