Initializing objects the clean way using the run scoping function
In this recipe, we are going to explore another useful extension function provided by the standard library, called run(). We are going to use it in order to create and set up an instance of the java.util.Calendar class.
Getting ready
First, let's explore the characteristics of the run() function defined in the standard library with the following function header:
public inline fun <T, R> T.run(block: T.() -> R): R
It is declared as an extension function for a generic type. The run function provides implicit this parameterinside the block argument and returns the result of the block execution.
How to do it...
- Declare an instance of the
Calendar.Builderclass and apply therun()function to it:
val calendar = Calendar.Builder().run {
build()
}- Add the desired properties to the builder:
val calendar = Calendar.Builder().run {
setCalendarType("iso8601")
setDate(2018, 1, 18)
setTimeZone(TimeZone.getTimeZone("GMT-8:00"...