How do I chain multiple scope functions together in Kotlin?

In Kotlin, scope functions can be chained because each one returns either:

  • the receiver object: also, apply
  • the lambda result: let, run, with

The key is understanding what each function returns.

Common chaining pattern

val result = User("Alice")
    .also {
        println("Created user: $it")
    }
    .apply {
        name = name.uppercase()
    }
    .let {
        "User name is ${it.name}"
    }

println(result)

Here:

  1. also receives the object as it and returns the same User
  2. apply receives the object as this and returns the same User
  3. let receives the object as it and returns the lambda result, a String

Example with a data class

data class User(var name: String, var age: Int = 0)

val description = User("Alice")
    .apply {
        age = 30
    }
    .also {
        println("Configured user: $it")
    }
    .run {
        "$name is $age years old"
    }

println(description)

Output:

Configured user: User(name=Alice, age=30)
Alice is 30 years old

Choosing the right scope function in a chain

Function Object reference Returns Common use
let it lambda result transform value, null checks
run this lambda result compute result from object
with this lambda result operate on existing object
apply this receiver object configure object
also it receiver object side effects like logging

Nullable chaining

Scope functions are especially useful with nullable values:

val length = maybeName
    ?.trim()
    ?.takeIf { it.isNotEmpty() }
    ?.also {
        println("Valid name: $it")
    }
    ?.let {
        it.length
    }

Here, the chain stops if any step returns null.

Practical example

val user = User(" alice ")
    .apply {
        name = name.trim()
    }
    .also {
        println("After trim: $it")
    }
    .apply {
        name = name.replaceFirstChar { it.uppercase() }
    }
    .also {
        println("Final user: $it")
    }

Rule of thumb

Use:

apply { }

when you want to configure an object and keep chaining the same object.

Use:

also { }

when you want to perform a side effect and keep chaining the same object.

Use:

let { }

or:

run { }

when you want to transform the object into another result.

So a typical chain often looks like:

val result = createObject()
    .apply {
        // configure object
    }
    .also {
        // log or validate
    }
    .let {
        // transform into final result
    }

How do I use run, apply, also, and with for cleaner Kotlin code?

In Kotlin, run, apply, also, and with are scope functions. They help make code cleaner by giving you a temporary scope around an object.

The main differences are:

Function Object reference Returns Best used for
apply this The original object Configuring an object
also it The original object Side effects, logging, validation
run this Lambda result Computing a result from an object
with this Lambda result Grouping operations on an object

apply: configure an object

Use apply when you want to initialize or configure an object and then keep using that same object.

val user = User().apply {
    name = "Alice"
    age = 30
    active = true
}

This is cleaner than:

val user = User()
user.name = "Alice"
user.age = 30
user.active = true

apply returns the original object:

val button = Button().apply {
    text = "Save"
    isEnabled = true
}

Use apply for:

  • object setup
  • builder-style initialization
  • setting multiple properties

also: perform side effects

Use also when you want to do something extra with an object without changing the main flow.

val user = repository.findUser(id)
    .also {
        logger.info("Loaded user: ${it.name}")
    }

also uses it and returns the original object.

Another example:

val numbers = mutableListOf<Int>()
    .also {
        println("Created list")
    }

Good use cases:

val file = File("data.txt")
    .also {
        require(it.exists()) { "File does not exist" }
    }

Use also for:

  • logging
  • debugging
  • validation
  • side effects that should not change the returned value

run: compute a result from an object

Use run when you want to execute code using an object and return a computed result.

val description = user.run {
    "$name is $age years old"
}

Here, run returns the last expression:

val length = "Kotlin".run {
    lowercase().length
}

run is useful when you want to avoid repeating the object name:

val isAdult = user.run {
    age >= 18
}

Use run for:

  • computing a value
  • using several properties/methods of an object
  • keeping temporary logic contained

with: group operations on an object

with is similar to run, but it is not called as an extension function.

val result = with(user) {
    "$name is $age years old"
}

This:

with(user) {
    println(name)
    println(age)
}

is cleaner than:

println(user.name)
println(user.age)

Use with when you already have an object and want to perform several operations with it.

val summary = with(order) {
    "Order $id has $itemCount items and costs $total"
}

Quick comparison

apply

val person = Person().apply {
    name = "Alice"
    age = 30
}

Meaning:

Configure this object and return the object.


also

val person = Person("Alice")
    .also {
        println("Created person: $it")
    }

Meaning:

Do something with this object and return the object.


run

val label = person.run {
    "$name ($age)"
}

Meaning:

Use this object to compute and return a result.


with

val label = with(person) {
    "$name ($age)"
}

Meaning:

With this object, compute and return a result.


Practical example

Without scope functions:

val request = Request()
request.url = "https://example.com"
request.method = "GET"
request.headers["Accept"] = "application/json"

logger.info("Created request: $request")

val summary = "Request to ${request.url} using ${request.method}"

With scope functions:

val request = Request().apply {
    url = "https://example.com"
    method = "GET"
    headers["Accept"] = "application/json"
}.also {
    logger.info("Created request: $it")
}

val summary = request.run {
    "Request to $url using $method"
}

Rule of thumb

Use this simple guide:

Need to configure an object?        apply
Need side effects like logging?     also
Need to compute a result?           run
Need to operate on an existing obj? with

Or more specifically:

  • Use apply when the lambda modifies or configures the receiver.
  • Use also when the lambda performs side effects and should not affect the returned value.
  • Use run when the lambda produces a new value.
  • Use with when you want to group operations on an existing object.

One warning: avoid overusing them

Scope functions can make code cleaner, but too many nested scope functions can make code harder to read.

Avoid this:

user.apply {
    address?.run {
        city.also {
            logger.info(it)
        }
    }
}

Prefer clearer code when nesting gets confusing:

val address = user.address ?: return
logger.info(address.city)

In short: scope functions are best when they reduce repetition and make intent obvious.

How do I combine multiple scope functions for concise Kotlin code?

In Kotlin, scope functions (like let, apply, also, run, and with) provide a way to execute a block of code within the context of an object. Combining them allows writing concise and readable code. Here’s how you can effectively use and combine them:

Example: Combining let and apply

Suppose you have an object that you need to both configure and process:

val result = myObject.apply {
    // Configure the object
    property1 = "value1"
    property2 = "value2"
}.let {
    // Use the configured object and transform it if needed
    it.someTransformingFunction()
}

Explanation:

  1. apply is used to mutate the object (configuration stage).
  2. let provides access to the configured object and performs further operations.

Example: Combining with and run

If you need to perform several actions on an object, including calculations:

val result = with(myObject) {
    // Perform actions on the object
    doAction1()
    doAction2()

    // Return something for further use
    this
}.run {
    // Execute more actions in the context of the returned object
    performAdditionalTask()
    finalResult()
}

Explanation:

  1. with is used as a concise way to operate on an object without changing its state, returning the object itself or another value.
  2. run is then used for further actions or transformations.

Example: Combining let and also

To perform logging or debugging while processing data:

val result = sourceString.let { input ->
    input.trim()
}.also { trimmed ->
    println("Trimmed string: $trimmed")
}

Explanation:

  1. let is used to create a pipeline where the string is transformed.
  2. also is used for side-effects, such as logging or debugging, without altering the object.

Example: Combining in Nested Chains

For a more complex scenario where multiple scope functions are needed:

val result = myObject.apply {
    property1 = "value1"
    property2 = "value2"
}.let {
    // Transform the configured object
    it.someTransformingFunction()
}.also {
    // Log the transformation
    println("Transformed object: $it")
}

This approach allows you to configure an object, transform it, and log its state in a single elegant chain.


General Guidelines

  • Use apply when you want to configure or initialize an object.
  • Use let when you want to execute a block of code with the object as a parameter and transform/compute something.
  • Use also when you need to perform a side effect (e.g., logging) while keeping the object unchanged.
  • Use run and with for blocks of code where you are mostly operating on the object and possibly returning a value.

By properly combining these scope functions, you achieve concise, clean, and functional Kotlin code!

How do I modified the value of LocalDate and LocalTime object?

The easiest way to modify the value of a LocalDate, LocalTime or LocalDateTime object is to use the with() method of the corresponding object. These methods will return a modified version of the object, it doesn’t change the attribute of the original object. All the methods, like withYear(), withDayOfMonth() or the with(ChronoField) of the LocalDate object will return a new object with the modified attribute.

With the LocalTime object you can use the withHour(), withMinute(), withSecond() or the more generic with(ChronoField) method to modified the attribute of a LocalTime object. You can also modified a LocalDateTime object using these with() method. Let’s see the example in the code snippet below.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;

public class ManipulatingDateTime {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2021, 4, 21);
        System.out.println("date1 = " + date1);
        LocalDate date2 = date1.withYear(2020);
        System.out.println("date2 = " + date2);
        LocalDate date3 = date2.withDayOfMonth(10);
        System.out.println("date3 = " + date3);
        LocalDate date4 = date3.with(ChronoField.MONTH_OF_YEAR, 12);
        System.out.println("date4 = " + date4);

        LocalTime time1 = LocalTime.of(1, 5, 10);
        System.out.println("time1 = " + time1);
        LocalTime time2 = time1.withHour(6);
        System.out.println("time2 = " + time2);
        LocalTime time3 = time2.withMinute(45);
        System.out.println("time3 = " + time3);
        LocalTime time4 = time3.with(ChronoField.SECOND_OF_MINUTE, 25);
        System.out.println("time4 = " + time4);

        LocalDate now1 = LocalDate.now();
        System.out.println("now1 = " + now1);
        LocalDate now2 = now1.plusWeeks(1);
        System.out.println("now2 = " + now2);
        LocalDate now3 = now2.minusMonths(2);
        System.out.println("now3 = " + now3);
        LocalDate now4 = now3.plus(15, ChronoUnit.DAYS);
        System.out.println("now4 = " + now4);
    }
}

The output of this code snippet are:

date1 = 2021-04-21
date2 = 2020-04-21
date3 = 2020-04-10
date4 = 2020-12-10
time1 = 01:05:10
time2 = 06:05:10
time3 = 06:45:10
time4 = 06:45:25
now1 = 2021-11-22
now2 = 2021-11-29
now3 = 2021-09-29
now4 = 2021-10-14

These with() methods is the counterpart of the get() methods. Where the get() methods will give you the value of the corresponding LocalDate or LocalTime attribute, the with() method will change the attribute value and return a new object. It didn’t call set because the object is immutable, which means it value cannot be changed.

While with the with() method you can change the value of date time attribute in an absolute way using the plus() or minus() method can help you change the date and time attribute in a relative way. The plus() and minus() method allows you to move a Temporal back or forward a give amount of time, defined by a number plus a TemporalUnit, in this case we use the ChronoUnit enumeration which implements this interface.