0Pricing
Kotlin Academy · Lesson

apply and also

Configure and side-effect.

Configuring Objects

apply and also are scope functions that return the object itself rather than the lambda result. This makes them perfect for configuration and chaining.

The apply Function

apply runs a block with the object as this and returns the object. It is the classic tool for initializing an object after creation.

fun main() {
    val builder = StringBuilder().apply {
        append("Hello")
        append(", ")
        append("World")
    }
    println(builder.toString())
}

All lessons in this course

  1. let and run
  2. apply and also
  3. with
  4. Choosing the Right One
← Back to Kotlin Academy