What apply() Looks Like

apply() is similar, though it is written as an extension function on T itself:

public inline fun <T> T.apply(block: T.() -> Unit): T {
    block()
    return this
}

Since apply() is an extension function of T, it can just call block() directly. this is already the correct receiver: the same object that apply() was called upon.

The other major difference is that with() returns the results of receiver.block(), while apply() returns this (the receiver).


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.