Kotlin let function

Kotlin has made our life very easy by providing features like extension functions, nullability check and much more. One such kind of really helpful feature is Scope functions. Once you understand what scope functions are, you will not able to resist yourself from using them.

This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-let-function/ and reposted on Medium on 26th Feb 2020.

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

To keep this article short and to the point, we will talk only about let in this article and all the use cases around it.

let scope function is used to apply operations on an object and finally return the lambda expression from that scope function. The return type can also be void.

To understand let function lets look at the implementation of let function first.

* Calls the specified function [block]
* with `this` value as its argument
* and returns its result.
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
return block(this)

let is an extension function to Template class which takes a lambda as a parameter, apply contract on it and ultimately return the execution of the lambda we passed as a parameter to it.

This clarifies a few things

Please continue reading at https://agrawalsuneet.github.io/blogs/kotlin-let-function/

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