Junior — Middle
What are the differences between the apply and with methods in terms of their usage and purpose?
sobes.tech AI
Answer from AI
In the context of Android (and Kotlin), apply and with are extension functions for convenient object manipulation, but they differ in usage and return value.
-
apply: Executes a block of code with the object as
thisand returns the object itself. Often used for object initialization. -
with: Takes an object and a block of code, executes the block with the object as
this, but returns the result of the last expression in the block.
Example:
val paint = Paint().apply {
color = Color.RED
strokeWidth = 10f
}
val length = with(paint) {
color.toString() + strokeWidth.toString()
}
Here, apply is convenient for configuring the object, and with is used for performing operations with the object and obtaining a result.