Kotlin scope function Let, Run, With, apply and also

Rahul Sharma
2 min readMay 3, 2021

What is the use ?

The main purpose is to execute a block of code within the context of an object. There are 5 scope function. I’ll keep this short and simple lets start without wasting more time

  1. Let

Used to check null, also better than simple null check in multi-threading and returns last line of this scope

var number: Int? = null     //initialize with some value for result
var result = number?.let { //lambda func with it:Int as param
var
square = it * it //'it' is copy of number
square //let will return last line
}

2. Also

Same as ‘Let’ but it doesn’t return the last line as ‘Let’, instead it returns the object it was called on.

var number: Int = 2         //init
number = (++number).also { //takes expression also
++it //return the object it called on"number"
}

3. Apply

Helpful function to modify objects, it uses ‘this’ instead of ‘it’ as we work inside Class of object

var intent = Intent().apply{this:Intent  //this means object intent
putExtra("", "") //putExtra of intent object
putExtra("","")
action = "" //return same object 'this'
}

4. Run

Equivalent to apply, but it won’t return the object it was called on, instead it will return the last line

var intent = Intent().run{
putExtra("", "")
putExtra("","")
action = "" //return last line
}

5. With

Same as ‘Run’ but with different signature

with(Intent()){            //with(arg) here with needs argument
putExtra("", "")
putExtra("","")
action = ""
}

All these scoped function do very similar things, but this make code more concise and readable.

I am available on linkedin for any question or feedback

--

--