Search⌘ K
AI Features

Scoping Functions

Explore Kotlin's scoping functions such as apply, let, run, and also to write concise, readable, and well-structured code. Understand how they control variable scope and improve object initialization and method invocation.

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:

Java
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:

Kotlin 1.5
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:

Kotlin 1.5
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 <T> T.apply(block: T.() -> Unit) : T

The function calls the passed ...