Sobes.tech
Middle

What standard delegates do you know?

sobes.tech AI

Answer from AI

  • by lazy — used for deferred initialization of a property. The value is computed upon the first access to the property and cached.
    val lazyValue: String by lazy {
        println("initialized") // Executes only on the first access
        "Hello"
    }
    
  • Delegates.observable — a delegate that allows executing an action every time the property's value changes.
    import kotlin.properties.Delegates
    
    var name: String by Delegates.observable("initial value") {
        prop, old, new ->
        println("Value changed for ${prop.name} from $old to $new")
    }
    
  • Delegates.vetoable — a delegate that intercepts changes to a property's value and can cancel the change based on a condition.
    import kotlin.properties.Delegates
    
    var age: Int by Delegates.vetoable(10) {
        prop, old, new ->
        new >= 0 // Only allow non-negative values
    }
    
What standard delegates do you know? — Android - sobes.tech