Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the use cases for `Delegates.observable` when we have property setters?

Tags:

What are the use cases for Delegates.observable when we can just use property setters?

 var foo by Delegates.observable("hell0") { prop, old, new ->     // react to changes in foo   }    var bar = "hello"     set(value) {       field = value       // react to changes in bar       // we can also do validation, set something like `value*2` to field, etc.     } 
like image 422
kptlronyttcna Avatar asked Apr 21 '18 21:04

kptlronyttcna


People also ask

What is the use of observable delegate?

The observable delegate allows for a lambda to be triggered any time the value of the property changes, for example allowing for change notifications or updating of other related properties: class ObservedProperty { var name: String by Delegates .observable ( "<not set>") { prop, old, new -> println ( "Old value: $old, New value: $new" ) } }

How do I delegate a getter and setter to another property?

A property can delegate its getter and setter to another property. Such delegation is available for both top-level and class properties (member and extension). The delegate property can be: To delegate a property to another property, use the :: qualifier in the delegate name, for example, this::delegate or MyClass::delegate.

How do I use delegated properties?

Delegated properties are used by declaring the property and the delegate that it uses. The by keyword indicates that the property is controlled by the provided delegate instead of its own field. This uses the fact that a MutableMap is itself a delegate, allowing you to treat its keys as properties. 3. Standard Delegated Properties

Why is the expression after by a property a delegate?

The expression after by is a delegate, because the get () (and set ()) that correspond to the property will be delegated to its getValue () and setValue () methods. Property delegates don’t have to implement an interface, but they have to provide a getValue () function (and setValue () for var s).


1 Answers

Property setters require much more code duplication if you want multiple properties to react to modification in the same way:

var foo: Foo = Foo()     set(value) {         println("foo = $value")         field = value     }  var bar: Bar = Bar()     set(value) {         println("bar = $value")         field = value     } 

Delegates, in turn, are aimed to allow for reuse of the property accessors logic, like this:

fun <T> printDelegate(init: T) =      Delegates.observable(init) { prop, _, new ->         println("${prop.name} = $new")     }  val foo: Foo by printDelegate(Foo()) val bar: Bar by printDelegate(Bar()) 
like image 142
hotkey Avatar answered Oct 05 '22 11:10

hotkey