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

  1. The return type of the let function is nothing but the same calling object.
  2. Since its an extension function to the Template class, it can be called on any object.

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store