Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: What is the difference between Apply and Also

Tags:

kotlin

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?

like image 490
Kanaiya Katarmal Avatar asked Sep 09 '17 13:09

Kanaiya Katarmal


People also ask

Why we use apply in Kotlin?

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.

What are scoping functions like with and apply let also?

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.

What is difference between let and run in Kotlin?

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.

How do I apply a function in Kotlin?

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.


1 Answers

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" } 

also

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.

apply

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.

when to use what

Usage examples are explained in this thread.

like image 96
s1m0nw1 Avatar answered Sep 17 '22 17:09

s1m0nw1