Scoping Functions
Get an introduction to the concept of scoping functions.
We'll cover the following...
Introduction
On the one hand, scoping functions offer the possibility of restricting the scope of variables. On the other hand, they lend a compact notation for bundling contextually related code in a clear and legible manner.
Often, we write code that first creates a new object and shortly thereafter invokes some of its methods or sets some properties.
In Java, this might look like this:
Press + to interact
Person person = new Person();person.setFirstName("Alex");person.setLastName("Prufrock");person.setDateOfBirth(1984,3,5);person.calculateAge();
Thanks to Kotlin’s properties, we can write this more elegantly:
Press + to interact
val person = Person()person.firstName = "Alex"person.lastName = "Prufrock"person.setDateOfBirth(1984,3,5)person.calculateAge()
It gets even better with the first possible scoping function called apply
:
Press + to interact
val person = Person().apply {firstName = "Alex"lastName = "Prufrock"setDateOfBirth(1984,3,5)}print("${person.firstName} ${person.lastName}\n${person.dob.year}-${person.dob.month}-${person.dob.day}")
This is what the signature of apply
looks like:
inline fun
...