“let”-“run”-“with”-“also”-“apply” — Kotlin scope functions.

Mohammed Audhil
AndroidPub
Published in
1 min readMar 2, 2020
TL;DRobj.let{it}, obj.run{this}, with(obj){this} - 
returns result of last line
obj.also{it}, obj.apply{this} -
returns the same object

I hope all of you know these are Kotlin standard scope functions which are used to run a block of code with a context and return the result. It took some time for me to understand the differences and nuances between them. It is classified based on the result that each function returns. All these functions are extension functions. Whereas run, and with can be used as a normal function as well.

fun returns “Result” — let, run, with

when we use the above functions, you can use the object within the block and returns whatever the last line of the block gives as a result.

let

let func — object is denoted as “it” inside block

run

run(as extension function) — object is denoted as “this”(optional) inside block
run (as block)

with

with func— object is denoted as “this”(optional) inside block

fun returns “this” — also, apply

when we use the above functions, you can use the object within the block and returns the same object(this)

also

also func— object is denoted as “it” inside block
also func — with custom object

apply

apply func — object is denoted as “this”(optional) inside block

Happy Coding!

--

--

Mohammed Audhil
AndroidPub

Software Engineer @Blackhawk_Networks | more: https://github.com/Audhil (Pray. Eat. Code. Sleep.)