Sobes.tech
Middle

What types of delegates exist in Kotlin?

sobes.tech AI

Answer from AI

  1. Property Delegates: Allow reusing common logic for getting/setting property values. Examples:

    • lazy: Lazy initialization of a property.
    • observable: Notifies about changes in the property value.
    • vetoable: Allows canceling a change in the property value.
    • Properties stored in a Map.
    // Lazy initialization
    val lazyValue: String by lazy {
        println("Calculating lazyValue...")
        "Hello"
    }
    
    // Observable property
    var name: String by Delegates.observable("initial value") {
        prop, old, new ->
        println("$old -> $new")
    }
    
  2. Delegating Implementation of Interfaces: Allows passing the implementation of an interface to another object. This is the "decorator" pattern.

    interface Base {
        fun print()
    }
    
    class BaseImpl(val x: Int) : Base {
        override fun print() {
            print(x)
        }
    }
    
    class Derived(b: Base) : Base by b // Delegating the implementation of Base
    
What types of delegates exist in Kotlin? — Android - sobes.tech