Built-in Standard Delegates
We'll cover the following...
Kotlin provides a few built-in delegates that we can readily benefit from. The Lazy delegate is useful to defer creating objects or executing computations until the time the result is truly needed. The observable
delegate is useful to observe or monitor changes to the value of a property. The vetoable
delegate can be used to reject changes to properties based on some rules or business logic. We’ll explore these features in this section.
It’s OK to get a little lazy
Decades ago John McCarthy introduced short-circuit evaluation to eliminate redundant computations in Boolean logic—the execution of an expression is skipped if the evaluation of an expression ahead of it is enough to yield the result. Most programming languages support this feature, and programmers quickly learn about the efficiency of this approach. The Lazy delegate pushes the boundaries of this approach—let’s see how. Suppose we have a function that gets the current temperature for a city (the following implementation merely returns a fake response):
fun getTemperature(city: String): Double {println("fetch from webservice for $city")return 30.0}
Calling this hypothetical function getTemperature()
is going to consume some time due to the remote access it requires to a web service. Also, there may be cost associated with the service usage. It’s better to avoid calls where possible. The short-circuit evaluation naturally does that, like in this example:
val showTemperature = falseval city = "Boulder"if (showTemperature && getTemperature(city) > 20) //(nothing here)println("Warm")elseprintln("Nothing to report") //Nothing to report
Since the value of showTemperature
variable is false
, due to short-circuit evaluation the execution of getTemperature()
method will be skipped. That’s efficient—if the result of a task isn’t used, we don’t bother doing that work. ...