Extension properties are a powerful feature in Kotlin that allow developers to add new properties to existing classes without modifying their source code. This capability enhances code readability and promotes a more modular approach to programming.
Extension properties provide a way to extend a class with new properties without inheriting from it or using design patterns like Decorator. They are defined outside the class but can be used as if they were part of the original class definition.
To define an extension property, use the following syntax:
val ClassName.propertyName: Type
get() = // property getter implementation
var ClassName.propertyName: Type
get() = // property getter implementation
set(value) { // property setter implementation }
Extension properties can be read-only (val) or mutable (var). They must have explicit getters and, for mutable properties, setters.
val String.lastChar: Char
get() = this[length - 1]
fun main() {
val str = "Hello"
println(str.lastChar) // Output: o
}
var ArrayList<Int>.lastEven: Int
get() = this.findLast { it % 2 == 0 } ?: throw NoSuchElementException("No even number found")
set(value) {
if (value % 2 != 0) throw IllegalArgumentException("Value must be even")
this.add(value)
}
fun main() {
val numbers = arrayListOf(1, 2, 3, 4, 5)
println(numbers.lastEven) // Output: 4
numbers.lastEven = 6
println(numbers) // Output: [1, 2, 3, 4, 5, 6]
}
Extension properties are closely related to Kotlin Extension Functions. While extension functions add new methods to existing classes, extension properties add new properties. Both features contribute to Kotlin's expressive and flexible nature.
For more advanced usage, you might want to explore Companion Object Extensions and Property Delegation in Kotlin.
Extension properties in Kotlin offer a powerful way to enhance existing classes with new properties. They promote code reusability and can significantly improve the readability and maintainability of your codebase. By mastering this feature, you'll be able to write more expressive and concise Kotlin code.