Kotlin Scoped Functions: let, run, with, also, apply

In this article, We are going to learn how to use scoped functions in kotlin programming language using some examples.

There are five scoped functions in kotlin: let, run, with, also, apply.

 

(1) let

let function returns the result of expression. Variables can not be used outside if they are declared inside the expression.

var playerName = “Cristiano Ronaldo”
     playerName.let { println(“The name of the Player is: $it”)
}

it keyword refers the variable inside let. We can also renamed it to readable lambda argument.

var playerName = “Cristiano Ronaldo”
     playerName.let { name -> println(“The name of the Player is: $name”)
}

let is also used with question mark to check value is null or not when obtaining a result. It is the most used scoped function in kotlin. If we use let then we do not need to check value is null or not with if loop.

var playerName: String? = “Cristiano Ronaldo”

     private fun getPlayerName() {
     val name = playerName?.let {
     “The name of the Player is: $it”
     }
     print(name)
}

 

(2) run

run is similar to let function but the difference is this keyword is used to refer variable instead of it. The other difference is we can not renamed this to readable variable.

var playerName = “Cristiano Ronaldo”
     playerName.let { println(“The name of the Player is: $it”)
}

run function can also be used to initialize variable and return the result.

var playerName1 = “Cristiano Ronaldo”
println(playerName1)

playerName1 = run {
     val playerName2 = “CR7”
     playerName2
}
println(playerName1)

 

(3) with

with is used to change value of variable without need to call dot operator every time. in with function, this keyword is used to refer the variable like run function. But for null safety, use of with function is difficult.

var playerName = “Cristiano Ronaldo”
println(playerName)

     with {
     playerName = “CR7”
}
println(playerName)

 

(4) also

also function is used to do some additional processing. also function uses it keyword to refer variable like let. But also function returns original value instead of any new value.

var playerName = “Cristiano Ronaldo”
println(playerName) //prints Cristiano Ronaldo

playerName = playerName.also {
     it = “CR7”
}
println(playerName) //prints Cristiano Ronaldo

 

(5) apply

apply function is same as run function in terms of refer variable by this keyword. But the difference is apply function does not accept any return statement.

var playerName = “Cristiano Ronaldo”
println(playerName)

 playerName.apply{
     this = “CR7”
}
println(playerName)

Leave a Reply