0% found this document useful (0 votes)
0 views

kotlin labsheet 3

This document is a lab sheet for a B.Tech CSE student named Sanjeevani, focusing on Android App Development. It includes questions and detailed solutions regarding Kotlin programming concepts such as higher-order functions, extension functions, sealed classes, delegation, operator overloading, reified types, memoization, and implementing timeout mechanisms. Each solution provides examples and explanations to illustrate the concepts effectively.

Uploaded by

vinitsingh5589
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

kotlin labsheet 3

This document is a lab sheet for a B.Tech CSE student named Sanjeevani, focusing on Android App Development. It includes questions and detailed solutions regarding Kotlin programming concepts such as higher-order functions, extension functions, sealed classes, delegation, operator overloading, reified types, memoization, and implementing timeout mechanisms. Each solution provides examples and explanations to illustrate the concepts effectively.

Uploaded by

vinitsingh5589
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

NAME- SANJEEVANI

BRANCH- B.TECH CSE


SEC- C
CU ID- CU24250141
ROLL NO- 62
SUBJECT- ANDROID APP DEVELOPMENT
SUBMITTED TO- MR. AKSHAY JUNEJA
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.

2. To create an extension function for a generic class:


class Box(val value: T)
fun Box.describe(): String {
return "Box contains: $value" }
fun main() {
val intBox = Box(42)
println(intBox.describe()) }

Advantages:
• Allows adding functions to existing generic classes without modifying them.
• Works with different data types seamlessly.

3. A sealed class restricts class inheritance to a defined set of subclasses, making it


useful for handling state management in Kotlin.
Example:
sealed class UiState {
object Loading : UiState()
data class Success(val data: String) : UiState()
data class Error(val message: String) : UiState() }
fun handleState(state: UiState)
{ when (state)
{ is UiState.Loading -> println("Loading...")
is UiState.Success -> println("Data: ${state.data}")
is UiState.Error -> println("Error: ${state.message}") } }

Advantages in State Management:


• Exhaustive when expressions ensure all cases are handled.
• Improves type safety by enforcing a fixed hierarchy.

4. Delegation allows a class to delegate responsibility to another class without


inheritance.
Example of Interface Delegation:
interface Logger {
fun log(message: String) }
class ConsoleLogger : Logger {
override fun log(message: String) {
println("Logging: $message") } }
class App(logger: Logger) : Logger by logger
fun main() {
val app = App(ConsoleLogger())
app.log("Hello") }

How it works:
• App delegates log to ConsoleLogger using by.
• Avoids boilerplate code while still implementing Logger.

5. Kotlin allows operator overloading using the operator keyword.


Example of overloading +:
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y) } }
fun main() {
val p1 = Point(2, 3)
val p2 = Point(4, 5)
println(p1 + p2) }
Why use it? .
Makes operations more intuitive (p1 + p2 instead of p1.add(p2)).

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.

7. Memoization stores previously computed values to avoid redundant calculations.


Example:
val cache = mutableMapOf<int,long>()
fun fibonacci(n: Int): Long {
if (n <= 1) return n.toLong()
return cache.getOrPut(n) { fibonacci(n - 1) + fibonacci(n - 2) } }
fun main() {
println(fibonacci(50)) }

How it improves efficiency:


• Prevents redundant recursive calls.
• Reduces time complexity from O(2ⁿ) to O(n).

8. Using Kotlin Coroutines, we can enforce a timeout with withTimeout.


Example:
import kotlinx.coroutines.*
suspend fun longRunningTask() {
delay(3000)
println("Task completed") }
fun main() = runBlocking {
try {
withTimeout(2000) {
longRunningTask() }
} catch (e: TimeoutCancellationException) { println("Task timed out!") } }

How it works:
• withTimeout(2000) cancels execution if it exceeds 2 seconds.
• Prevents indefinitely running tasks.

You might also like