androidengineers.Book a session
โ† All interview questions
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."
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."
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).

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising