Complete the code to declare an observable property with initial value 10.
var score: Int by [1](10) { prop, old, new -> println("Score changed from $old to $new") }
The Delegates.observable function creates an observable property that calls the lambda whenever the value changes.
Complete the code to print the old and new values when the property changes.
var name: String by Delegates.observable("John") { [1], old, new -> println("Name changed from $old to $new") }
The lambda receives three parameters: the property, the old value, and the new value. The property parameter is commonly named prop.
Fix the error in the observable delegate usage.
var age: Int by Delegates.observable([1]) { prop, old, new -> println("Age changed from $old to $new") }
The initial value must be an Int, so 25 without quotes is correct. Quotes make it a String, causing a type error.
Fill both blanks to create an observable property that prints a message only when the new value is greater than the old value.
var level: Int by Delegates.observable(1) { prop, old, new -> if (new [1] old) { println("Level increased to $new") } }
The condition new > old checks if the new value is greater than the old one, triggering the print only on increase.
Fill the two blanks to create an observable property that prints the change only when the new value is different from the old value.
var status: String by Delegates.observable("idle") { [1], old, new -> if (new [2] old) { println("Status changed from $old to $new") } }
The lambda receives three parameters: the property (named prop), the old value, and the new value. The condition new != old ensures printing only on actual changes.