Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Extension Properties in Kotlin

What are Extension Properties?

Extension properties are a powerful feature in Kotlin that allows you to add new properties to existing classes without modifying their source code. They enable you to enhance the functionality of classes, making your code more flexible and reusable. Extension properties can be especially useful in scenarios where you want to add utility functions or properties to classes from third-party libraries.

Defining Extension Properties

An extension property is defined similarly to a regular property but with the class name prefixed to the property name. The syntax is as follows:

val ClassName.propertyName: PropertyType

The property can have a custom getter, and it can also have a setter if it is defined as a mutable property.

Example of Extension Properties

Let's illustrate how to create and use an extension property. In this example, we will create an extension property for the String class that returns the length of a string in words.

val String.wordCount: Int
    get() = this.split("\\s+".toRegex()).size

In this code, we define an extension property wordCount for the String class. The getter splits the string into words using a regular expression and returns the size of the resulting list.

Using the Extension Property

Now that we have defined the extension property, let's see how we can use it:

fun main() {
    val text = "Hello Kotlin Extension Properties"
    println("Word Count: ${text.wordCount}")
}

When we run this code, it will output the word count of the string:

Word Count: 5

Mutable Extension Properties

You can also define mutable extension properties. However, note that mutable extension properties can only be added to classes that you have control over, as you need to implement the backing field. Here's how you can do it:

var StringBuilder.lastChar: Char
    get() = this[this.length - 1]
    set(value) {
        this.setCharAt(this.length - 1, value)
    }

In this example, we define a mutable extension property lastChar for the StringBuilder class. This property allows you to get and set the last character of the string builder.

Using the Mutable Extension Property

Here’s how to use the mutable extension property we just defined:

fun main() {
    val sb = StringBuilder("Hello")
    println("Last Char: ${sb.lastChar}")
    sb.lastChar = '!'
    println("Updated String: $sb")
}

Running this code will produce the following output:

Last Char: o
Updated String: Hell!

Conclusion

Extension properties in Kotlin are an elegant way to add new properties to existing classes. They enhance the capabilities of classes without the need to modify their source code, making your code cleaner and more maintainable. Whether you are adding utility functions or modifying existing functionality, extension properties provide a significant advantage in Kotlin programming.