Junior — Middle
How to add functionality to a class without modifying its source code?
sobes.tech AI
Answer from AI
To add functionality to a class without modifying its original code in Android (Java/Kotlin), you can use several approaches:
-
Inheritance — create a subclass and extend or override the necessary methods.
-
Delegation — create a new class that contains an instance of the original class and implements additional functionality by forwarding calls.
-
Extension functions (in Kotlin) — allow adding new methods to existing classes without inheritance or modifying the original code.
Example of an extension function in Kotlin:
// Adding a function to the String class
fun String.isEmailValid(): Boolean {
return this.contains("@") && this.contains(".")
}
// Usage
val email = "test@example.com"
println(email.isEmailValid()) // true
Thus, extension functions are a convenient way to extend the functionality of classes in Android without changing their original code.