Sobes.tech
Middle

What is the feature of property delegates?

sobes.tech AI

Answer from AI

Property delegates in Kotlin allow you to delegate the logic of getting and setting a property's value to a separate helper class called a delegate.

Features:

  1. Understanding getValue and setValue: For read-only properties (val), the delegate must have a getValue method. For read-write properties (var), the delegate must have both getValue and setValue. These methods take as parameters:

    • A reference to the object containing the property (for class members).
    • Metadata about the property as a KProperty object.
  2. Standard delegates: Kotlin provides several standard delegates:

    • lazy: For lazy initialization of a property.
    • observable: To perform some action when the property's value changes.
    • vetoable: To perform some action when the property's value changes, with the ability to veto the change.
    • Map delegates: The property can be stored in a Map.
  3. Custom delegates: You can create your own delegate classes. The class must implement the ReadOnlyProperty (for val) or ReadWriteProperty (for var) interfaces.

Example of using lazy:

// The field is initialized only upon first access
val lazyValue: String by lazy { 
    println("Calculating value")
    "Hello"
}

Example of using observable:

import kotlin.properties.Delegates

var name: String by Delegates.observable("<no name>") {
    property, oldValue, newValue ->
    println("$oldValue -> $newValue")
}

Example of a custom delegate:

import kotlin.reflect.KProperty

class Delegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "$thisRef, property '${property.name}' value"
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$thisRef, property '${property.name}' changed to '$value'")
    }
}

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