0Pricing
Kotlin Academy · Lesson

apply and with: Configure and Return

Use apply and with to configure objects and understand their return values.

Scope Function Recap

Kotlin's scope functions (apply, also, let, run, with) let you execute a block in the context of an object. Each differs by receiver (this vs it) and return value.

apply Basics

apply { ... } runs the block with this bound to the receiver and returns the receiver itself. Perfect for object configuration.

class Person {
    var name: String = ""
    var age: Int = 0
}
fun main() {
    val p = Person().apply {
        name = "Ada"
        age = 35
    }
    println("${p.name}, ${p.age}")
}

All lessons in this course

  1. apply and with: Configure and Return
  2. let and run: Transform and Scope
  3. also: Side Effects Without Changing the Receiver
  4. Choosing the Right Scope Function: Decision Guide
← Back to Kotlin Academy