Custom delegates
- Kotlin course
- Intermediate
- Lesson 74/116
- 5 min
Learn to write your own property delegates.
Custom delegates
You can write your own delegate class. For a read-only property define operator fun getValue(thisRef: Any?, property: KProperty<*>): T. Example: class Single(val v: Int) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = v }. Then use it with val x by Single(42).
For a read-write property add operator fun setValue too. You may implement the ReadOnlyProperty or ReadWriteProperty interfaces, but writing the operator functions is enough. This is a powerful way to fully control behavior.
The getValue operator
When a delegate class defines operator fun getValue, it can be bound to a property with the by keyword. Example: class Single(val v: Int) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = v }.
Usage: val x by Single(42). Every access to x calls getValue and returns 42. thisRef is the property owner (may be null), property is the property reference. This simple example returns a constant; more complex delegates can cache, log or compute.
Practice Define the Single delegate
Add import kotlin.reflect.KProperty. Define class Single(val v: Int) with operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = v inside. In main define val x by Single(42) and call println(x).
Starter code
import kotlin.reflect.KProperty
// Define the Single class: with the getValue operator
fun main() {
// Define x with the Single(42) delegate and print
}Sample solution
import kotlin.reflect.KProperty
class Single(val v: Int) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = v
}
fun main() {
val x by Single(42)
println(x)
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the custom delegate parts
| Term | Meaning |
|---|---|
ReadOnlyProperty |
Read-only |
ReadWriteProperty |
Read-write |
getValue |
Read |
setValue |
Write |
2 Complete the getValue body
class Single(val v: Int) {
operator fun getValue(thisRef: Any?, p: KProperty<*>): Int = ____
}
class Single(val v: Int) {
operator fun getValue(thisRef: Any?, p: KProperty<*>): Int = v
}
Explanation: getValue returns the v value.
3 Which operator does a read-only custom delegate require?
- getValue Correct answer
- setValue
- both
- neither
Explanation: A read-only delegate requires only getValue.