Development
-
February 10, 2020

Scope functions in Kotlin

The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called scope functions. There are five of them: let, run, with, apply, and also. [source]

When and how to use scope functions [.c-inline-code]run, let, apply, also, with[.c-inline-code] in Kotlin in order to improve our productivity writing a clean, readable and easy to maintain code.

Objectives.

. Work with the same scope.. Write clean, readable and easy to maintain code

- run:

Receives [.c-inline-code]this[.c-inline-code] as an instance of the current object and returns a final value.

It is recommended for execute actions over the same scope.

Without "run" the code looks like:

- let:

Receives [.c-inline-code]it[.c-inline-code] as an instance of the current object and returns a final value, It is recommended for use the object scope several times with others functions.

- apply:

Receives [.c-inline-code]this[.c-inline-code] as an instance of the current object and returns the object.

It is recommended for change the scope function data:

- also:

Receives [.c-inline-code]it[.c-inline-code] as an instance of the object, returns the same [.c-inline-code]scope(object)[.c-inline-code] as result.

It is recommended for execute a code after a creation of the object or parameters assignations:

Also, you can chain with [.c-inline-code]apply[.c-inline-code]:

- with:

Similar to let, but using [.c-inline-code]this[.c-inline-code] as scope.

It is recommended if you know the object is not null for example:

If you need to check the object’s nullability you should use [.c-inline-code]let[.c-inline-code] instead of [.c-inline-code]with[.c-inline-code]:

Combining scope functions

Imagine you have two objects and you need to nest scope functions.

In this case you need to specify the name of the scope to avoid overlapping.

Summary:

Should be use scope functions depending on your needs, there is not a specific rule for each one, they are used in order to have a clean and easy to maintain code, and since Kotlin is a compiled language with the use of those functions you can get better performance of your apps.

Learn more

Kotlin Scope Functions (https://kotlinlang.org/docs/reference/scope-functions.html)