Interview frequency: …
Short answer
They differ in how the object is referenced (this or it) and in the returned value (the object itself, the context object, or the lambda result).
Explanation
apply and also are used to initialize the object and perform side effects and return the object itself (the context object), where apply uses the reference this while also uses the parameter it. let, run, and with return the result of the lambda expression; let with it is used for null checks and transformation, run with this to group operations and compute a value, while with takes the object as a separate parameter.
Code example
// apply: Initialize the object and return it
val intent = Intent().apply {
action = Intent.ACTION_VIEW
data = Uri.parse("https://developer.android.com")
}
// let: Check for null, cast the type, and return the result
val length = text?.let { it.trim().length } ?: 0
// also: Perform logging or side effects and return the object
val user = createUser().also { log("User created: ${it.id}") }Common mistakes
- Nesting more than one scope function in a complex way, making the code ambiguous and hard to read and maintain.
- Using let only for a null check when if (x != null) is simpler and clearer (there is no performance difference because let is an inline function; the difference is only in readability).