What if you could add new properties to any class instantly, without changing its original code?
Why Extension properties in Kotlin? - Purpose & Use Cases
Imagine you want to add a new feature to a class you didn't create, like adding a shortcut to get the full name from a Person object. Without extension properties, you'd have to create a new subclass or write helper functions everywhere.
Manually creating subclasses or helper functions is slow and clutters your code. It also makes your code harder to read and maintain because the new feature isn't directly tied to the original class.
Extension properties let you add new properties to existing classes without changing their code. This keeps your code clean and lets you use the new property just like a regular one.
fun getFullName(person: Person): String = person.firstName + " " + person.lastNameval Person.fullName: String get() = "$firstName $lastName"You can enhance existing classes with new, easy-to-use properties that feel like they belong there, making your code simpler and more expressive.
Adding a fullName property to a Person class lets you write person.fullName instead of calling a separate function, making your code cleaner and easier to understand.
Extension properties add new properties to existing classes without modifying them.
They keep your code clean and easy to read.
They help you write more natural and expressive code.