The apply() function

The apply() function simply executes the function or given block with its own reference as the receiver, and returns the same updated object.

The apply() function is defined something like this. The block function always has a reference to the object for which apply() is called:

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

If we break the prototype of the preceding function, this means it takes this (its own reference as a parameter and executes all the functions and property calls over it and returns the updated object).

The following two lines demonstrate how android activity can be started and destroyed:

activity.startActivity(intent)activity.finish()

It can be written as follows using apply(). Not a typical ...

Get Hands-On Serverless Applications with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.