What is Extension Property in Kotlin: Simple Explanation and Example
extension property in Kotlin allows you to add a new property to an existing class without modifying its source code. It works like an extension function but provides a way to access a value as if it were a regular property on the class.How It Works
Imagine you have a smartphone but want to add a new feature, like a flashlight, without opening the phone and changing its hardware. Extension properties in Kotlin work similarly: they let you add new properties to existing classes from the outside, without changing the original class.
Technically, extension properties do not actually insert new fields into the class. Instead, they provide getter (and optionally setter) methods that behave like properties. When you access an extension property, Kotlin calls these methods behind the scenes.
This means you can write code that looks like you're accessing a normal property, but Kotlin runs your custom code instead. This helps keep your code clean and lets you add useful features to classes you don't own.
Example
This example shows how to add an extension property lastChar to the String class that returns the last character of the string.
val String.lastChar: Char
get() = this[this.length - 1]
fun main() {
val name = "Kotlin"
println(name.lastChar) // Accessing the extension property
}When to Use
Use extension properties when you want to add convenient, read-only or computed properties to classes without changing their code. This is especially useful for classes from libraries or the Kotlin standard library.
For example, you might add an extension property to calculate a value based on existing data, like the last character of a string, the size of a collection in a special way, or a formatted version of a date.
Remember, extension properties cannot hold state because they don't add real fields. They are best for computed or derived values.
Key Points
- Extension properties add new properties to existing classes without modifying them.
- They use getter (and optionally setter) methods, not real fields.
- They are useful for computed or derived values.
- You cannot store data in extension properties because they don't add fields.
- They improve code readability and reuse by adding handy properties.