What are Scope functions?
Kotlin provides functions known as Scope functions in the standard library to execute a block of code within the context of an object.
It offers a temporary scope when you call the function on the object with a lambda expression. In Scope, the function can access the object without its name.
There are five scope functions we'll cover in this blog.
- Let
- Run
- With
- Apply
- Also
Scope represents the lambda expression to create a temporary scope. Hence, It's called Scope functions. It has Object access to its functions without its name.
Example: Without using scope function.
Output
Example: With using the scope function
Output
Application of using scope function
Scope functions make code clear, readable, and concise in application.
As we have discussed above, there are five types of scope functions
- let
- run
- with
- apply
- Also
Each of their functions is similar but has minor differences. It is very useful in applications.
1. Let function
Context object: it
Return value: lambda result
Let function is used to provide null safety calls. So I used a safe call operator(?). It executes the block only with the non-null value.
Example:
Output
2. Apply function
Context object: this
Return value: context result
Apply these to the object it can be used to operate on members.
Example:
Output
3. With function
Context object: this
Return value: lambda result
Use a calling function on a context object without providing the lambda result.
Example:
4. run function
Context object: this
Return value: lambda result
The run function is used as a combination of let and with functions.
Example:
Output
5. also function
Context object: this
Return value: context result
It is used where we have to perform additional operations.
Example:
Output
In conclusion, you have learned the process in the above steps for how Kotlin Scope works. As discussed above, Kotlin scope functions improve readability and make the code clear and concise.