One of the most important features of Kotlin is its ability to create scopes for object initialization and configuration. To achieve this, Kotlin has two methods: the apply() and with() methods.
Using either of these methods can help reduce the amount of code needed to accomplish the desired goal. With practice, developers can quickly become familiar with how to use these methods in their code.
When "apply" & When "with"?
The apply() method takes a single receiver object and creates a scope in which that object is initialized and configured. This allows the object to be modified without needing to explicitly reference the object, and the function can perform complex logic before returning the object, with the changes included.
On the other hand, with() creates a scope for multiple objects. This allows for a more complex object configuration, as each argument is evaluated in the same scope. Each object is initialized and configured within the with() block and the result is a single object with the results of all the configured arguments. This method is great when initializing and configuring multiple objects as it reduces the amount of code needed to do so.
Difference between “apply” and “with”
The main difference between "apply" and "with" is the scope of the function. Apply takes a function and an array of arguments and applies the arguments to the function. With takes an object and creates a new scope for the function that is being called. With allows for a shorter syntax for referencing properties of the object.
Example of apply in kotlin
fun main(args: Array<String>) {
val numbers = listOf(1, 2, 3, 4, 5)
numbers.apply {
val sum = this.sum()
println(sum)
}
}
// Output: 15
Example of with in kotlin
fun main(args: Array<String>) {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
with(numbers) {
println(sum())
}
}
// Output: 55.0
Conclusion
When using the apply and with functions in Kotlin, they differ in the way they handle the object they are applied to. The apply function applies an action to the object and then returns the object itself. The with function applies an action to the object and then returns the result of that action. Therefore, the apply function is best used when you want to modify the object itself and the with function is best used when you want to return a result from the object.