Author profile picture

also() (scope function)

Overview

The also() function is a scope function that was introduced in Kotlin 1.1.

Example

val size = "Hello".also {
    println(it)
}.length

In this example, the string “Hello” is printed, and then its length is assigned to the size variable.

Characteristics

When the also() extension function executes:

  • the receiver object that .also() is called upon is available as the lambda argument - by default, named it
  • the result will be the receiver object

Create, Pass, and Evaluate

A prime use case for also() is the pattern where you need to pass an empty object to another function for initialization. For example, to get the DisplayMetrics in Android, you create a new DisplayMetrics object, and pass it into the getMetrics() method. Then afterward you can evaluate the properties on it.

// Create the object
DisplayMetrics metrics = new DisplayMetrics();

// Pass it to getMetrics(), which sets the values on it
activity.getWindowManager()
        .getDefaultDisplay()
        .getMetrics(metrics);

// Evaluate the property
System.out.println(metrics.density);

Kotlin’s also() method simplifies this pattern:

println(DisplayMetrics().also {
    activity.windowManager
            .defaultDisplay
            .getMetrics(it)
}.density)

Alternatives

To help you decide between the different scope functions, take a look at the guide, Understanding Kotlin’s let(), also(), run(), and apply().

Share this article:

  • Share on Twitter
  • Share on Facebook
  • Share on Reddit