Saturday 13 November 2021

Vetoable - Delegates -- Kotlin

Vetoable, this allows us to modify the values when the argument input by the user(s) fulfills the specified condition, it can be used in place of observable properties if the user wants to intercept assignment. Vetoable is like Observable Properties with additional features to allows to modify and notify the values when the condition is met.

Simple example: 

The string which you never want to be reassigned with empty or to some specific text. 

The number values which is assigned should be match some condition.  

The generic observable kind of where the condition check will happen and then the value will be get assigned to the variable, incase if the condition fails, older value will be retained. 

var acceptOnlyEven: Int by Delegates.vetoable(0) { property, prevStr, nextStr ->
        nextStr.mod(2) == 0
}

var allowNonEmptyText: String by Delegates.vetoable("NA") { property, oldValue, newValue ->
        newValue.isNotEmpty()
}

var acceptStatus: String by Delegates.vetoable(STATUS_START) { property, oldValue, newValue ->
        listOf(STATUS_START, STATUS_INPROGRESS, STATUS_DONE).contains(newValue)
}

println("Str: $acceptStatus")
acceptStatus = "Status"
println("Str: $acceptStatus")
acceptStatus = ""
println("Str: $acceptStatus")
acceptStatus = "DonE"
println("Str: $acceptStatus")
acceptStatus = "Done"
println("Str: $acceptStatus")

println("Value: $acceptOnlyEven")
acceptOnlyEven = 10
println("Value: $acceptOnlyEven")
acceptOnlyEven = 5
println("Value: $acceptOnlyEven")

println("Str: $allowNonEmptyText")
allowNonEmptyText = "Status"
println("Str: $allowNonEmptyText")
allowNonEmptyText = ""
println("Str: $allowNonEmptyText")

Output:

Str: Start
Str: Start
Str: Start
Str: Start
Str: Done
Value: 0
Value: 10
Value: 10
Str: NA
Str: Status
Str: Status

Good Luck, Happy Coding :-)

No comments: