Mallow's Blog

A BRIEF INTRODUCTION TO KOTLIN SCOPE FUNCTIONS

Earlier we have given a brief overview on Kotlin and now we follow up with one of the interesting topics in Kotlin i.e Scope functions. Scope functions help us in the process of simplifying the logics used in the block. The Kotlin standard library contains several functions and purpose of each is to execute a block of code within the given context. The Scope function is also similar to other functions with the difference that it takes on an object with a lambda expression which forms a temporary scope and we can access the object without its name.

The Scope functions are of five types as
1) let
2) with
3) run
4) apply
5) also

There are mainly two difference between each scope function. They are :
1) The way to refer the context of the object
2) The return value

Context object :
Each scope function uses one of the two ways to access the context object : this & it. this is called lambda receiver & it is called lambda argument. We will see in more detailed way about its usage in the below examples. 

Return value :
1) apply & also return the context object.
2) let, run & with return the lambda result.

Let’s now dive deep into the scope function types & its usage

let
The context object is available as an argument (it). The return value is the lambda result. The let function is used to execute block of code, access its parameter using it and returns the value which is present in the last line (optional). The let function can also be used as an alternative for if block using safe call operator (?.) as below.

Example :

fun main() {
    val str: String? = "Hello"   
	val length = str?.let { 
    	println("$it World")        
	    it.length // Returns the length
	}
    println(length)
}

Output :

Hello World
5


with
with is a non-extension function. The context object is passed as an argument and it is available as a receiver (this). The return value is the lambda result. It is similar to let with the difference that this is used as context object instead of it.

Example :

fun main() {
    val numbers = mutableListOf("apple", "orange", "grapes")
    with(numbers) {
        println("$this")
        println("${this.size}")
    }
}

Output :

[apple, orange, grapes]
3


run
The context object is available as a receiver (this). The return value is the lambda result. The run scope function is useful when our lambda contains both the object initialisation and the computation of the return value.

Example :

fun main() {
    val text: String? = “Hello World”
    val len = text?.run {
        println(“Get length of $this")
        length //`this` can be omitted
    } 
    println("Length of $text is $len")
}

Output :

Get length of Hello World
Length of Hello World is 11


apply
The context object is available as receiver (this). The return value is the object itself. The apply block is mainly used when we don’t worry about returning a value and instead mainly operate on members of the receiver object. We can use apply for the simplification of the complex chains of blocks.

Example :

data class Student(var name: String, var age: Int = 0, var city: String = "")
fun main() {
    val student = Student("Alex").apply {
        age = 20
        city = "Chennai"        
    }
    println(student)
}

Output :

Student(name=Alex, age=20, city=Chennai)


also
The context object is available as an argument (it). The return value is the object itself. The also block is used mainly for printing, logging & having reference of the passed object. It is not used for altering the object.

Example :

fun main() {
    val planets = mutableListOf("Mercury", "Venus", "Earth")
planets
    .also { println("The planets so far: $it") }
    .add("Mars")
}

Output :

The planets so far: [Mercury, Venus, Earth]

Thus we have seen in detail about the Kotlin Scope functions. In order to make it clearer you can see the below image which simplifies each scope function usage & how to use.

Kotlin Scope Functions|Mallow-tech


Bringe Raj,
Android Development Team,
Mallow Technologies.

REFERENCE :

https://kotlinlang.org/docs/reference/scope-functions.html
https://proandroiddev.com/kotlin-standard-functions-just-another-guide-8c639181ceb1
https://en.proft.me/2018/11/7/scoping-functions-kotlin/

Leave a Reply

%d bloggers like this: