January 2018
Intermediate to advanced
434 pages
14h 1m
English
The apply function is quite similar to the also function, but they have a subtle difference. To understand that, let's look at their implementation first:
The also function:
public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
In also, the block is defined as (T) -> Unit, but it is defined as T.() -> Unit in apply(), which means there is an implicit this inside the apply block. However, to reference it in also, we need it.
So a code using also will look like this:
val result = Dog(12).also { it.age = 13 }
The same will look like this using apply:
val result2 =Dog(12).apply {age = 13 }
The age ...
Read now
Unlock full access