Sobes.tech
Junior

What is the purpose of using extensions in Kotlin?

sobes.tech AI

Answer from AI

The purpose of extensions in Kotlin is to add new functionality to existing classes without inheriting from them or using the decorator pattern. This makes the code more readable and concise, especially when working with libraries that cannot be modified.

For example:

// Creating an extension for Int
fun Int.isPositive(): Boolean {
    return this > 0
}

// Using the extension
val number = 5
if (number.isPositive()) {
    // ...
}
// Extension for List<T>
fun <T> List<T>.firstOrEmpty(): T? {
    return ifEmpty { null } // Using a standard function, but through an extension
}

val myList = listOf(1, 2, 3)
val firstElement = myList.firstOrEmpty()