What are scope functions in Kotlin? How to use them!!
November 16, 2024
Kotlin scope function ( let, run, with, apply, also )
Basically, these functions all perform the same action: execute a block of code on an object
When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name.
How Scope functions differ
1-The way they refer to the context object ( this or it )
2-Return value ( return the context object. or return the lambda result.)
Note: Context object (a lambda receiver (this) , lambda argument (it) )
Explanation of each Scope function
Let
use case : Executing a lambda on non-nullable objects
use case : Introducing an expression as a variable in local scope
1-The context object is available as an argument (it).
2-The return value is the lambda result.
Example:
val numbers = mutableListOf("one", "two", "three", "four", "five")
val resultList = numbers.map { it.length }.filter { it > 3 }
println(resultList)
val numbers1 = listOf("one", "two", "three", "four")
val modifiedFirstItem = numbers1.first().let { firstItem ->
println("The first item of the list is '$firstItem'")
if (firstItem.length >= 5) firstItem else "!" + firstItem + "!"
}.uppercase()
println("First item after modifications: '$modifiedFirstItem'")
With
use case: Grouping function calls on an object
1-The context object is available as a receiver (this).
2-The return value is the lambda result.
Example:
val numbers2 = mutableListOf("one", "two", "three")
with(numbers2) {
println("'with' is called with argument $this")
}
val numbers3 = mutableListOf("one", "two", "three")
val firstAndLast = with(numbers3) {
"The first element is ${first()}," +
" the last element is ${last()}"
}
println(firstAndLast)
Run
use case : Object configuration and computing the result
use case : Running statements where an expression is required: non-extension run
1-The context object is available as a receiver (this).
2-The return value is the lambda result.
Example:
val str = "Hello"
// this
str.run {
println("The string's length: $length")
//println("The string's length: ${this.length}") // does the same
}
Apply
use case : Object configuration
1-The context object is available as a receiver (this).
2-The return value is the object itself.
Example:
val adam = Person("Adam").apply {
age = 32
city = "London"
}
println(adam)
result : Person(name=Adam, age=32, city=London)
Also
use case: Additional effects
1-The context object is available as an argument (it).
2-The return value is the object itself.
val numbers4 = mutableListOf("one", "two", "three")
numbers4
.also { println("The list elements before adding new one: $it") }
.add("four")