Sobes.tech
Junior — Middle

Can you add a new property to an existing class using extension, and how?

sobes.tech AI

Answer from AI

In Kotlin (commonly used for Android development), you can add a new property to an existing class using extension properties. However, it is important to remember that extension properties cannot store state, meaning they cannot have their own field for storing a value. They are implemented through getters and setters, which usually use the existing data of the object.

Example of adding an extension property:

val String.firstChar: Char
    get() = this[0]

// Usage:
val letter = "Hello".firstChar  // 'H'

If you need to add a truly new stored property, this is not possible through extensions. For that, inheritance or composition should be used.