kotlin labsheet 3
kotlin labsheet 3
Question-: 1. What is a higher-order function in Kotlin, and how does the inline keyword
optimize its performance?
2. How do you create an extension function for a generic class in Kotlin, and what is its
advantage?
3. What is a sealed class in Kotlin, and how does it help in state management?
4. How does Kotlin’s delegation mechanism work, and how can it be used to implement
interface delegation?
5. What is operator overloading in Kotlin, and how can you overload the + operator for a
custom class?
6. What is a reified type in Kotlin, and why is it useful in inline functions?
7. How does memoization improve the efficiency of the Fibonacci sequence calculation in
Kotlin?
8. How can you implement a timeout mechanism in Kotlin to limit the execution time of a
task?
Solution-:
1. A higher-order function is a function that takes another function as a parameter or
returns a function.
Example:
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b) }
fun main() {
val sum = operateOnNumbers(4, 5) { x, y -> x + y }
println(sum) }
Optimization with inline When passing lambda expressions to higher-order functions,
Kotlin creates an object to store the lambda, which may lead to overhead. The inline
keyword eliminates this overhead by inlining the function body at the call site:
inline fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int { return
operation(a, b) }
This prevents function object creation and improves performance.
Advantages:
• Allows adding functions to existing generic classes without modifying them.
• Works with different data types seamlessly.
How it works:
• App delegates log to ConsoleLogger using by.
• Avoids boilerplate code while still implementing Logger.
6. Kotlin normally erases generic types at runtime (type erasure). However, reified
allows access to the actual type inside an inline function.
Example:
inline fun printType() {
println("Type: ${T::class}") }
fun main() {
printType() }
Why is it useful?
• Enables checking types at runtime (if (T::class == String::class)).
• Makes generics more powerful without reflection.
How it works:
• withTimeout(2000) cancels execution if it exceeds 2 seconds.
• Prevents indefinitely running tasks.