Kotlin: What is the difference between Apply and Also

What is the difference between application as well. From what I know, the following code does the same:

To 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 a difference and should I use one over the other? In addition, are there any cases where it would be possible to work, and the other not?

+21
source share
3 answers

TL DR difference

alsothe function gets the lambda to which it Tis passed in the implementation, so inside the lambda you will access it with a name ( itby default, you can rename it { otherName ->...}).

val person = Person().also {
    it.name = "Tony Stark"
}

apply, , , , . this.

val person = Person().apply {
    name = "Tony Stark"
}

:

inline fun <T> T.also(block: (T) -> Unit): T (source)

this () this ().

:

inline fun <T> T.apply(block: T.() -> Unit): T (source)

this this ().

.

+19

: also .

:

apply, this.

val person = Person().apply {
    name = "Tony Stark" // this. can be omitted
    age = 52 // this. can be omitted
    // ...
}

, , :

person.name = "Tony Stark"
person.age = 52

, this . also . it, . , , ( person) :

val person = Person().also { newPerson ->
  newPerson.name = "Tony Stark"
  newPerson.age = 52
  // ...
}

, , , .

+15

, , , . , .

Standard.kt .

/**
 * Calls the specified function [block] with `this` value as its receiver and returns `this` value.
 */
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

,

/**
 * Calls the specified function [block] with `this` value as its argument and returns `this` value.
 */
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block(this)
    return this
}

The two methods are almost the same except for one line. Only after explanation did I see the difference. A functional language like Kotlin is really complicated for a like-minded Java like me.

+1
source

All Articles