Kotlin apply function
--
In continuation to my previous post where I explained about Kotlin let scope function, let’s try to understand today about apply function today.
This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-apply-function/ and reposted on Medium on 29th April 2020.
Just to recap, Scope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.
There are a few scope functions
- let
- with
- run
- apply
- also
To keep this article short and to the point, we will talk only about apply in this article and all the use cases around it.
apply scope function is used to configure the object once initialized and returns the object itself. The context object is available inside the apply function as this
.
To understand apply function lets look at the implementation of appy function first.
/**
* Calls the specified function [block] with `this` value as its receiver and returns `this` value.
*
*/
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
apply an extension function to Template class which takes a lambda as a parameter, apply contract on it, execute the lambda function within the scope of calling object and ultimately return the same object of Template class itself
This clarifies a few things
- The return type of the let function is nothing but the same calling object.
- Since its an extension function to the Template class, it can be called on any object.