Kotlin Idioms Use apply to initialize objects or to achieve method chaining


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 so helpful apply is indeed an useful function. In layman's terms apply establishes a scope in which this is bound to the object you called apply on. This enables you to spare some code when you need to call multiple methods on an object which you will then return later. Example:

File(dir).apply { mkdirs() }

This is the same as writing this:

fun makeDir(String path): File {
    val result = new File(path)
    return result