Sobes.tech
Junior — Middle

How to extend the functionality of an object or class using extensions?

sobes.tech AI

Answer from AI

In Android (more precisely in Kotlin, which is often used for Android development), extensions allow you to add new functions or properties to existing classes without the need for inheritance or modifying the original source code.

This is done using the fun keyword for extension functions or val/var for extension properties.

Example of an extension function for the String class:

fun String.isEmailValid(): Boolean {
    return this.contains("@") && this.contains(".")
}

// Usage:
val email = "test@example.com"
println(email.isEmailValid())  // true

Thus, extensions make it convenient to add functionality to classes, making the code more readable and modular.

How to extend the functionality of an object or class… - sobes.tech