Sobes.tech
Middle

What are delegate properties in Kotlin?

sobes.tech AI

Answer from AI

Delegated properties are a way to delegate the logic of getting (get) and setting (set) a property's value to another object. This allows for extracting repetitive code and making classes more concise.

Main components:

  • Delegate: An object that implements the ReadOnlyProperty interface (for val) or ReadWriteProperty (for var). It contains the logic for getValue() and optionally setValue().
  • by operator: A keyword in Kotlin used to bind a property to its delegate.

Examples of standard delegates:

  • lazy: The property is initialized only upon first access.
    // Example of lazy delegate
    val lazyValue: String by lazy {
        println("initialized")
        "Hello"
    }
    
  • delegates.observable: Executes an action after each assignment to the property.
    // Example of observable delegate
    var name: String by kotlin.properties.Delegates.observable("<no name>") {
        prop, old, new ->
        println("$old -> $new")
    }
    
  • delegates.vetoable: Allows intercepting the assignment and canceling it if a condition is not met.
    // Example of vetoable delegate
    var age: Int by kotlin.properties.Delegates.vetoable(0) {
        prop, old, new -> new >= 0
    }
    
  • Delegating to another property: You can delegate a property to another property.
    // Example of delegating to another property
    var text: String = "Original"
    var delegatedText: String by ::text
    

Creating custom delegates:

You need to implement the ReadOnlyProperty or ReadWriteProperty interface.

// Example of a custom ReadWriteProperty delegate
import kotlin.reflect.KProperty

class ExampleDelegate {
    private var value: String = ""

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        println("$thisRef, thank you for delegating '${property.name}' to me!")
        return value
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$thisRef, thank you for delegating '${property.name}' to me!")
        this.value = value
    }
}

class Example {
    var p: String by ExampleDelegate()
}

Advantages:

  • Reuse of getter/setter logic.
  • Improved code readability.
  • Reduction of boilerplate.
  • Clean API for working with properties.
What are delegate properties in Kotlin? — Kotlin - sobes.tech