Kotlin Standard functions or Scoping functions: (let, apply, run, also, with)

Kishan Maurya
ProAndroidDev
Published in
3 min readAug 30, 2019

--

In this article, we are going to learn how to use these 5 scope functions. Many of us have already used these functions. So what we need to learn about them

How we should use them?
and when we should use them?

The way they perform, sometimes become the cause of confusion.

let's learn more about them. We will take the example of webview.
so we will set few properties of the webview.

with
It is convenient when you have to call multiple different methods on the same object. Instead of repeating the variable containing this object on each line, you can use with.
with
is used to change instance properties without the need to call dot operator over the reference every time.

This is a normal function.
It is not an extension function.
last expression of with function returns a result.

let
Use let whenever you want to define a variable for a specific scope of your code but not beyond.

So in this example setting variable cant’ be used outside let block.
so the problem of variable leak out will not happen here.

This can also be used as an alternative to testing against null: like if webView.settings is null then this block will not execute.
let is useful for checking Nullable properties.

We can chain multiple let functions.

run
Run is actually a combination of with() and let().

It is same as let if webView.settings is null then this block will not execute
It is same as with call multiple different methods on the same object

We can chain multiple run functions.

also
It passes an object as a parameter and returns the same object.
It returns the original object which means the return data has always the same type

T.also returns the T itself i.e. this
T.also let you perform on the same variable i.e. this.

also in combination with let

also in combination with run

apply
It is an extension function. It runs on the object reference (also known as a receiver) into the expression and returns the object reference on completion.

In apply it isn’t allowed.
It sends this as it’s an argument.
It returns this (i.e. itself)

apply in combination with let

apply in combination with run

Summary of the post :

Feel free to share some good real example of how you use these functions as a response to this blog.

You could check out my other interesting topics here.

--

--