Kotlin Extension Properties 🎯

beginner
20 min

Kotlin Extension Properties 🎯

Welcome to the Kotlin Extension Properties tutorial! In this lesson, we'll explore how to extend classes and objects in Kotlin using extension properties. This concept is a powerful tool for making your code more expressive and easier to read.

By the end of this lesson, you'll be able to:

  • Understand what extension properties are and why they're useful
  • Create your own extension properties
  • Use extension properties in practical examples

What are Extension Properties? 📝

Extension properties allow you to add new properties to existing classes or objects, without actually modifying the original class definition. This means you can extend the functionality of a class without inheriting from it or implementing any interfaces.

This feature makes your code cleaner and more modular, as you can add new behaviors to existing classes without modifying their source code.

Creating an Extension Property 💡

To create an extension property, you use the val or var keyword followed by the name of the property, a type, and the get and set keywords. Here's an example:

kotlin
import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty class StringLength : ReadWriteProperty<String, Int> { override operator fun getValue(thisRef: Any, property: KProperty<*>) = thisRef.toString().length override operator fun setValue(thisRef: Any, value: Int, property: KProperty<*>) { thisRef.toString().padStart(value, ' ') } } val String.lengthExtension: Int get() { return this as String by StringLength() } set(value) { this = this.toString().padStart(value, ' ') }

In the example above, we've created an extension property called lengthExtension for the String class. It provides a get method to retrieve the length of a string and a set method to set the length of a string.

Using Extension Properties 💡

Now that you've created an extension property, let's use it in a practical example:

kotlin
fun main() { val myString = "Hello, World!" // Retrieve the length of the string println("The length of the string is ${myString.lengthExtension}") // Set the length of the string to 10 myString.lengthExtension = 10 println("The new string is: $myString") }

In this example, we've defined a main function and created a myString variable of type String. We then use the lengthExtension extension property to get the length of the string and set the length of the string to 10.

Quiz

Quick Quiz
Question 1 of 1

What is an extension property in Kotlin?

Quick Quiz
Question 1 of 1

How do you create an extension property in Kotlin?