In Kotlin, we can create an extension property just like we create extension functions. An extension property is a property that can be added to an existing class without actually modifying the class itself.
Here’s an example of creating an extension property for the ‘String‘ class:
// Define the extension property
val String.customLength: Int
get() = this.length + 5
// Use the extension property on a String instance
fun main() {
val str = "hello"
println(str.customLength) // Output: 10
}
In the above code, we have created an extension property called ‘customLength‘ for the ‘String‘ class. This extension property adds 5 to the length of the string and returns the result.
To define an extension property, we need to prefix the property name with the class name and use the ‘val‘ or ‘var‘ keyword to specify if the property is read-only or mutable, respectively. The implementation of the property is defined in its getter function, which is accessed using the ‘get()‘ method.
In the ‘main‘ function, we have created a ‘String‘ instance named ‘str‘ and accessed the ‘customLength‘ property on it. The output of this property call is 10, which is the length of the string "hello" plus 5.
Overall, extension properties in Kotlin provide a convenient way to add new properties to existing classes and extend their functionality without modifying those classes directly.