What is Scope Function in Kotlin?
In Kotlin, the scope function is not a built-in function. However, there are several scope functions available in Kotlin that help in defining a temporary scope for an object, allowing you to perform operations on it without the need to create intermediate variables. These scope functions are: let, run, with, apply, and also. Check the youtube video
Here's a brief overview of each scope function:
val data = "Sample"
val result = data.let {
// Perform operations on it
// Return the result
val level = data + "One"
level.substring(0,1)
}
- Context Object : 'it'
- Return Value : Lambda result
- Context Object : 'this'
- Return Value : Lambda result
run: It is similar to let, but the object is accessed through the this keyword within the block. It returns the result of the block.val data = "Sample"
val result = data.run {
// Perform operations on it
// Return the result
val level = data + "One"
level.substring(0,1)
}
- Context Object : 'this'
- Return Value : Lambda result
apply: It allows you to configure the properties of an object and returns the object itself. The object is accessed using the this keyword within the block.val intent = Intent().apply {
putExtra("Type", "user")
putExtra("Value", "normal")
setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
startActivity(intent)
- Context Object : 'this'
- Return Value : Context Object
also: It is similar to apply, but it does not return the object itself. Instead, it returns the original object. It is often used for performing additional actions on an object, such as logging or side effects.val intent = Intent().also {
it.putExtra("Type", "user")
it.putExtra("Value", "normal")
it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
startActivity(intent)
- Context Object : 'it'
- Return Value : Context Object
Thank you for reading this blog. Hope this will be use full to you. Follow for more blog like this.