Kotlin: What is the difference between Apply and Also

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)