Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
211: Property Delegation: Custom Delegate Classes
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
BoundedIntclass must implementReadWriteProperty<Any?, Int>. - The constructor should take
min: Intandmax: Int. - The
setValuemethod must implement the clamping logic. - Create a
Playerclass with ahealthproperty delegated toBoundedIntwith a range of 0 to 100. - In your
mainfunction, assign 150 tohealthand verify it is clamped to 100, then assign -50 and verify it is clamped to 0.
There are no comments for now.