Property delegation in Kotlin
Level 5344 keystrokes
With by, a property hands its get and set to a delegate. Delegates.observable calls a handler after each change, and Delegates.vetoable calls one before the change and only accepts the new value when it returns true, so age = -5 is rejected.
Kotlin code
// Import the standard delegates1import kotlin.properties.Delegates2 3class User { // observable: starts as "Unknown"; the handler gets the property, the old and the new value4 var name: String by Delegates.observable("Unknown") { _, old, new -> // Runs after every assignment5 println("Name: $old -> $new")6 } // vetoable: starts at 0; the handler decides whether the new value is accepted7 var age: Int by Delegates.vetoable(0) { _, _, new -> // Accept only non-negative values; false keeps the old value8 new >= 09 }10}11 // Create a user with the initial values12val user = User()// Prints Name: Unknown -> Alice13user.name = "Alice"// Prints Name: Alice -> Bob14user.name = "Bob"// 25 >= 0, so it is accepted15user.age = 25// Rejected: age stays 2516user.age = -5// Prints Final: Bob, 2517println("Final: ${user.name}, ${user.age}")Output
Name: Unknown -> Alice Name: Alice -> Bob Final: Bob, 25
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
.× 10"× 10=× 6,× 5(× 5)× 5{× 5}× 5-× 4:× 4