Member-only story
Simple Way to Understand Kotlin Scope Functions — let, run, with, apply, also
You have no idea when to use them because they are confusing. This article explains the common practical usages of these Scope functions.
5 min readJan 28, 2022
If you look at the scope function examples in my previous post here, you can clearly tell that all those Kotlin Scope Functions (i.e. let
, run
, with
, apply
, also
) can accomplish the same thing. They're all interchangeable, with slightly different in syntax.
Syntax Differences
Let’s understand the syntax differences between them first.
Source: kotlinlang.org
Note 1: All these scope functions are extension functions except for run
and with
. There are 2 run
scope functions. One is with extension and another one without the extension function.
val str = "test"
// let, run, also, apply - are "extension functions"
str.run {
println(this)
}
// with - is NOT an "extension function"
with(str) {
println(this)
}
// run - could be NOT an "extension function"
run {
println(str)
}