What is the difference between apply and also. From what I know the following code does the same thing:
apply
val person = Person().apply { name = "Tony Stark" age = 52 // More such stuff }
also
val person = Person().also { it.name = "Tony Stark" it.age = 52 // More such stuff }
Is there any difference and should I use one over the other? Also, are there some cases where one would work and the other won't?
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 with.
In this scope, you can access the object without its name. Such functions are called scope functions. There are five of them: let , run , with , apply , and also . Basically, these functions do the same: execute a block of code on an object.
Kotlin run expression can change the outer property. Hence in the above code, we've redefined it for the local scope. Similar to the let function, the run function also returns the last statement. Unlike let, the run function doesn't support the it keyword.
apply is an extension function to Template class which takes a lambda as a parameter, apply contract on it, execute the lambda function within the scope of calling object and ultimately return the same calling object of Template class itself.
TL;DR Difference
The also
function takes a lambda in which you refer to the object you called the function on (receiver T
) with either it
(implicit name) or a custom name.
val person = Person().also { it.name = "Tony Stark" }
With apply
, on the other hand, a function literal with receiver is used so inside the passed in lambda you can access the receiver’s members directly, as you see in the following. The receiver can be referenced by this
.
val person = Person().apply { name = "Tony Stark" }
Declaration:
inline fun <T> T.also(block: (T) -> Unit): T (source)
Calls the specified function block with this
(the receiver) value as its argument and returns this
(the receiver) value.
Declaration:
inline fun <T> T.apply(block: T.() -> Unit): T (source)
Calls the specified function block with this
value as its receiver and returns this
(the receiver) value.
Usage examples are explained in this thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With