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