Kotlin scope functions for dummies! 🤪

Kaaveh Mohamedi
Kt. Academy
Published in
2 min readAug 27, 2023

--

I want to know all Kotlin scope functions but I’m sooooo dumb! let’s learn it in a dummy way!

Photo by Sander Sammy on Unsplash

Apply

“apply the following assignments to the object.”

It is good for object configuration or implementing a code in the Builder design pattern style. For example:

// Normal approach
fun createIntent(intentData: String, intentAction: String): Intent {
val intent = Intent()
intent.action = intentAction
intent.data = Uri.parse(intentData)
return intent
}

// Improved approach, by using apply
fun createIntent(intentData: String, intentAction: String) =
Intent().apply {
action = intentAction
data = Uri.parse(intentData)
}

Also

“and also do the following with the object.”

If in any case of chaining operations you want some additional effects such as logging. For example:

val numberList = mutableListOf<Double>()

numberList
.also { println("Populating the list") }
.apply {
add(2.71)
add(3.14)
add(1.0)
}
.also { println("The ${it.size} items added to the list") }
.also { println("Sorting the list") }
.sort()
.also { println("The list sorted") }

Let

“let’s do the following stuff with it”

let helps us to do stuff with an object without define a variable:

// Without let we must define a variable
val alice = Person("Alice", 20, "Amsterdam")
println(alice)
alice.moveTo("London")
alice.incrementAge()
println(alice)

// But with let, we can scape it!
Person("Alice", 20, "Amsterdam").let {
println(it)
it.moveTo("London")
it.incrementAge()
println(it)
}

Or simply helps on null check:

val str: String? = "Hello"

processNonNullString(str) // compilation error: str can be null

val length = str?.let {
println("let() called on $it")
processNonNullString(it) // OK: 'it' is not null inside '?.let { }'
it.length
}

With

“with this object, do the following.”

For calling functions on the context object when you don’t need to use the returned result, Like binding in Android:

with(binding){
emptyView.gone()
errorView.gone()
userList.visible()
}

Run

“run the code block and return the result”

There is two kind of run:

  1. The extension function version
  2. The non-extension one

The extension function version

“The with in extension function style!”

Object configuration and computing the result:

val service = MultiportService("https://example.kotlinlang.org", 80)

val result = service.run {
port = 8080
query(prepareRequest() + " to port $port")
}

// the same code written with let() function:
val letResult = service.let {
it.port = 8080
it.query(it.prepareRequest() + " to port ${it.port}")
}

The non-extension one

“Grouping some temporary local variables for a calculation”

val hexNumberRegex = run {
val digits = "0-9"
val hexDigits = "A-Fa-f"
val sign = "+-"

Regex("[$sign]?[$digits$hexDigits]+")
}

--

--