🚀 Enrollments Open for 1:1 Mentorship Scheduled as per your availability 💚Book 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.

1:1 Mentorship

Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.

Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance

Limited slots available each month

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow 💚