0
0
Kotlinprogramming~3 mins

Why Extension properties in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add new properties to any class instantly, without changing its original code?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
fun getFullName(person: Person): String = person.firstName + " " + person.lastName
After
val Person.fullName: String get() = "$firstName $lastName"
What It Enables

You can enhance existing classes with new, easy-to-use properties that feel like they belong there, making your code simpler and more expressive.

Real Life Example

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.

Key Takeaways

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.