๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Apply and Also

apply and also are scope functions that return the value they were called on. apply sets up a value, and also adds a side step such as a print.

apply builds a list

The block adds items to the list through the receiver. apply returns that same list.

fun main() {
    val numbers = mutableListOf(1, 2)
    val same = numbers.apply {
        add(3)
        add(4)
    }
    println(numbers)
    println(same)
}

apply configures an object

The block sets two properties on the settings object. The configured object is the result.

class Settings {
    var volume = 0
    var muted = false
}

fun main() {
    val settings = Settings().apply {
        volume = 8
        muted = true
    }
    println(settings.volume)
    println(settings.muted)
}

also inside a chain

also prints the word and passes it on unchanged. The uppercase call then runs on the same word.

fun main() {
    val text = "kotlin"
        .also {
            println(it)
        }
        .uppercase()
    println(text)
}

also prints a warning

The also block checks the age and prints a warning. The age itself passes through unchanged.

fun main() {
    val age = 15.also {
        if (it < 18) {
            println("Too young")
        }
    }
    println(age)
}

Example

fun main() {
    val cart = mutableListOf("milk")
    cart.apply {
        add("eggs")
        add("rice")
    }.also {
        println("Items: ${it.size}")
    }
    println(cart)
}

Key points

  • apply makes the value the receiver inside the block.
  • apply returns the receiver itself after the block runs.
  • also makes the value available as it inside the block.
  • also returns the original value after the block runs.
  • A chain can pass through also and keep its value.

In this example, apply adds two items to the cart and returns the cart. also then prints the item count for that cart. The last line prints the full list.

Note

Use apply to configure a value. Use also for an extra step that should not change the value.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does apply return?