Use apply to initialize objects or to achieve method chaining
suggest changeThe 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
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents