Kotlin: Apply vs With

Here are the Similarities and Differences

Similarities

With and Apply both accept an object as a receiver in whatever manner they are passed.

Differences

With returns the last line in the lambda as the result of the expression.

Apply returns the object that was passed in as the receiver as the result of the lambda expression.

Examples

With

private val ORIENTATIONS = with(SparseIntArray()) {
    append(Surface.ROTATION_0, 90)
    append(Surface.ROTATION_90, 0)
    append(Surface.ROTATION_180, 270)
    append(Surface.ROTATION_270, 180)
}
ORIENTATIONS[0] // doesn't work 
// Here, using with prevents me from accessing the items in the SparseArray because, 
// the last line actually returns nothing

Apply

private val ORIENTATIONS = SparseIntArray().apply {
    append(Surface.ROTATION_0, 90)
    append(Surface.ROTATION_90, 0)
    append(Surface.ROTATION_180, 270)
    append(Surface.ROTATION_270, 180)
}
ORIENTATIONS[0] // Works
// Here, using apply, allows me to access the items in the SparseArray because, 
// the SparseArray is returned as the result of the expression

There're two differences:

  1. apply accepts an instance as the receiver while with requires an instance to be passed as an argument. In both cases the instance will become this within a block.

  2. apply returns the receiver and with returns a result of the last expression within its block.

I'm not sure there can be some strict rules on which function to choose. Usually you use apply when you need to do something with an object and return it. And when you need to perform some operations on an object and return some other object you can use either with or run. I prefer run because it's more readable in my opinion but it's a matter of taste.

Tags:

Kotlin