Junior — Middle
Explain the concept of Extensions in Kotlin and their usage.
sobes.tech AI
Answer from AI
In Kotlin, Extensions allow you to add new functions or properties to existing classes without the need for inheritance or modifying the original class code.
This is especially useful when you need to extend the functionality of classes from libraries or the standard library.
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
Extensions cannot directly modify the state of an object, as they do not add new fields but only allow calling additional methods as if they belong to the class.
Thus, Extensions help write more readable and convenient code, expanding the capabilities of existing classes without inheritance.