Skip to content

Delegation : By using Vetoable

Devrath edited this page Feb 28, 2024 · 1 revision

Observation

  • Note here every time we try to modify the variable just like observable oldValue, newValue is printed.
  • But the distinction here is in the vetoable block, We can add a condition that determines that when the value can be set.

Code

class MainActivity : ComponentActivity()
{

    private var demoObject by Delegates.vetoable(initialValue = 5) { property, oldValue, newValue ->
        println("OldValue:---> $oldValue")
        println("NewValue:---> $newValue")
        newValue>5
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        demoObject = 2
        println("Result Accessed:-> $demoObject")
        println("< ----------------- >")
        demoObject = 9
        println("Result Accessed:-> $demoObject")

        setContent {}
    }

}

Output

OldValue:---> 5
NewValue:---> 2
Result Accessed:-> 5
< ----------------- >
OldValue:---> 5
NewValue:---> 9
Result Accessed:-> 9
Clone this wiki locally