Junior — Middle
How was the addition of methods to existing classes in Kotlin implemented using extensions?
sobes.tech AI
Answer from AI
In Kotlin, adding methods to existing classes is implemented through extension functions. This allows "extending" classes with new functions without the need for inheritance or modifying the original class code.
Extensions are declared outside the class, specifying the type they are added to, and look like regular functions but with a receiver — the object of the extended type.
Example of an extension for the String class:
fun String.lastChar(): Char = this[this.length - 1]
val c = "Kotlin".lastChar() // 'n'
Thus, extensions allow calling new methods as if they are part of the class, which is convenient for improving code readability and organization, especially when working with libraries and APIs where the original class cannot be changed.