Use apply to initialize objects or to achieve method chaining

suggest change

The documentation of apply says the following:

calls the specified function block with this value as its receiver and returns this value.

While the KDoc is not especially helpful, apply is a useful function. In plain terms, apply establishes a scope in which this is bound to the object you called apply on. That saves code when you need to call multiple methods on an object and then return that object. Example:

File(dir).apply { mkdirs() }

This is the same as writing:

fun makeDir(path: String): File {
    val result = File(path)
    result.mkdirs()
    return result
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents