🚀 Enrollments Open for Jetpack Compose Cohort 2 — 7 Days of Live Learning to Build Modern Android UIs 💚Join Now
KotlinIntermediate4 min
How to choose between apply and with?

Answer

Both are scope functions, but they differ in object reference and return value.

apply

  • Object Reference: `this`
  • Return Value: The object itself.
  • Use Case: Object configuration / initialization. "Apply these settings to the object."

```kotlin val intent = Intent().apply { action = Intent.ACTION_VIEW data = Uri.parse("https://google.com") } // Returns the configured Intent ```

with

  • Object Reference: `this`
  • Return Value: The result of the lambda (last line).
  • Use Case: Performing multiple operations on an object without returning it. "With this object, do these things."

```kotlin val length = with(person) { println(name) println(age) name.length // Returns this Int } ```

Quick Rule

  • Need the object back? Use apply.
  • Need a result from the object? Use with (or run).

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

Accelerate Your Growth

Don't just learn concepts in isolation. Build production-ready Android apps with expert guidance.

Live Interactive Sessions
Code Reviews & Feedback
Real-world Projects
Career Guidance

Limited seats available for next cohort