Skip to Content
Course content

211: Property Delegation: Custom Delegate Classes

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen a lot of developers hit a wall when they move from using built-in delegates like lazy or observable to writing their own. Usually, it's because they treat a delegate like a standard wrapper class rather than a specialized operator. Let's look at a common scenario: you want a property that automatically trims whitespace from any string assigned to it.

The "Operator" Oversight

class TrimmedString {
    private var internalValue: String = ""

    fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): String {
        return internalValue
    }

    fun setValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>, value: String) {
        internalValue = value.trim()
    }
}

class UserProfile {
    var nickname: String by TrimmedString()
}

fun main() {
    val profile = UserProfile()
    profile.nickname = "  KotlinAce  "
    println("'${profile.nickname}'") // Expecting 'KotlinAce'
}

If you try to compile this, the compiler is going to scream at you. It'll tell you that TrimmedString doesn't provide a getValue operator function. You're looking at the code thinking, "But I literally wrote a function called getValue right there!"

Here is the thing: in Kotlin, property delegation isn't just about having a method with the right name. It's a specific language feature that relies on operator overloading. Without the operator keyword, the by keyword has no idea how to connect the property access to your class methods.

Connecting the Delegate to the Property

To fix this, we need to explicitly tell Kotlin that these functions are intended to handle the property's getter and setter. I also want to point out that KProperty<*> is passed in. Even if you don't use it now, Kotlin requires it because the delegate needs to know which property it's currently managing (which is vital if you use the same delegate instance for multiple properties).

class TrimmedString {
    private var internalValue: String = ""

    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): String {
        return internalValue
    }

    operator fun setValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>, value: String) {
        internalValue = value.trim()
    }
}

Now the code compiles and works. But honestly? Writing those signatures out manually every time is a chore and makes the code look cluttered. It's a bit of a boilerplate nightmare.

Cleaning up with ReadWriteProperty

Kotlin provides a couple of interfaces to make this cleaner: ReadOnlyProperty and ReadWriteProperty. When you implement ReadWriteProperty, you don't have to manually write the operator signatures; the interface handles the heavy lifting for you. You just implement the logic.

I prefer this approach because it forces you to be explicit about the types of the object owning the property (the thisRef) and the type of the property itself.

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class TrimmedString : ReadWriteProperty<Any?, String> {
    private var internalValue: String = ""

    override fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return internalValue
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        internalValue = value.trim()
    }
}

By using ReadWriteProperty<Any?, String>, we're saying: "This delegate can be used in any class (Any?) and it manages a property of type String." It's much more readable and less prone to typos in the function signatures. If you only need a read-only property, just use ReadOnlyProperty and skip the setValue implementation entirely.




📋 Practical Task

Building a Range-Validated Integer Delegate

You need to create a custom property delegate called BoundedInt. This delegate should ensure that an integer property always stays within a specific minimum and maximum range. If a value is assigned that is outside this range, the delegate should "clamp" the value (i.e., if the value is too high, set it to the maximum; if it's too low, set it to the minimum).

Requirements:

  • The BoundedInt class must implement ReadWriteProperty<Any?, Int>.
  • The constructor should take min: Int and max: Int.
  • The setValue method must implement the clamping logic.
  • Create a Player class with a health property delegated to BoundedInt with a range of 0 to 100.
  • In your main function, assign 150 to health and verify it is clamped to 100, then assign -50 and verify it is clamped to 0.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.