As per kotlin documentation -> The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of 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.
So what this means is that , scope functions are functions that let you access the attributes of an object without using name and also lets us manipulate it.
The 5 scope functions are
- with
- let
- apply
- also
- run
Lets see the major use case for these scope functions
For the sake of the example lets take sample object called Car
class Car {
var company:String? = null
var model:String? = null
var mileage:Float? = 0.0f
}
And we have an object car which can be null or some value
val car = null
//OR
val car = Car()
- If the property is nullable, we can use let or run
car?.run {
// data is available using this keyword
mileage = 60f
this.company = "BMW"
model = "X1"
}
car?.let {
// receiver is available using it keyword
it.mileage = 60f
it.company = "BMW"
it.model = "X1"
}
2. If we want to access all the details without referencing the object name we can use with
//Instead for the below
val mil = car.mileage
val com = car.company
val mod = car.model//We can use the below
with(car!!){
// data is available using this keyword
val mil = mileage
val com = company
val mod = model
}
3. We can use also when we want to do some additional work with an object or the result of some other function or expression.
// Example for additional work on result of function
var triplePrice = ""
val price = 20.plus(10).also {
triplePrice = "Triple Price is ${it * 2}"
}
4. We can use apply when we want to add something once the object is created.
val intent = Intent().apply {
putExtra("SomeKey", "Some value")
putExtra("AnotherKey", "Another value")
action = "SOME_APP_ACTION"
}
If you like this short article and would like a deep dive article into the inner working of scope functions please clap and follow.
Happy Coding!