Kotlin

Kotlin Scope Functions

When we are using a lambda expression to invoke methods on an object, the temporary scope is generated. In the article, we will discuss the concept of scope functions. The Scope Functions are the name for these functions. These functions’ objects are accessible without knowing their names.

What are the Types of Scope Functions in Kotlin?

Scope functions make our code much more legible, concise, and straightforward, all of which are important attributes of the Kotlin programming language. When we don’t use the scope function, we have to type the name of the object every time we want to refer to a class member. But we can refer to members without providing the object name when utilizing the scope function. We have five scope functions in general, all of which are very similar with slight differences.

  1. let
  2. run
  3. apply
  4. with
  5. also

How to Use the Kotlin Scope Functions?

To understand the basics of using the different scope functions in the Kotlin language, you should take a look at the following examples:

Example # 1: Using the “Let” Scope Function in Kotlin

The Let function is frequently used to execute a code block with non-null values only. We have to use the safety operator “?.” on a non-null object. Let’s use the let function in the below code.

We have the main function. In the main function block, we have a variable as “val ” keyword and defined as “str1” . The variable “str1” set with the Int type property and safety null operator is used to check whether the value is null or not. As we have initialized the variable “str1” with the integer value that is not null. Then, we have to use the let function for “str1”. In the let function block, we have passed a keyword “it” as a parameter in println function which is act as a context object. After that, we have another variable defined as “str2” and has a property of String type. The null safety operator is used here too for checking the nullability. The “str2” is declared with the string value. Now, using the let function which will return “str2” values as it is not null. Here, we have simply passed “str2” to the println function.

The output of using the let function is displayed on the below screen.

Example # 2: Using the “Apply” scope Function in Kotlin

The apply function is used to work on receiver object members primarily to initialize them. The apply function to code blocks that return an object itself and the keyword “this” is the context object here.

In the above code, we have created a class “Employee” in which we have defined lateinit variables. The lateinit variable is a variable that is late initialized. We have three lateinit variables for the class “Employee” as “empName”, “empContact”, and “empDept” and set the String type property for these defined variables. Then, we have to call the main function in which we have used the apply function. In the apply function, we have the “this” keyword used with the variable “empName”. The keyword “this” serves as an object reference and contains the string as its initialization value. We have also initialized the variables “empContact” and “empDept” with the particular values. The “this” keyword works the same as the other variable declared in the code. Through the println function, we will have the printed values.

The output of the apply function is shown on the terminal screen.

Example # 3: Using the “With” Scope Function in Kotlin

When invoking functions on context objects without giving the lambda result, use of “with” function is recommended.

We have a class “Person” in which we have defined the lateinit variables. The variables are assigned a name “Name” and “Age” and set the String type property. Then, we have the main function in which we have created an object named “p1”. The object “p1” is invoking the apply function. In the apply function, we have initialized the variable “Name” and “Age” with the values. After this, we have invoked the “with” function and passed an object “p1” as a parameter to it. Note that we didn’t use “${Name}” and “${Age}” in the println function because it would be redundant because the block of code recognizes that “Name” and “Age” is used in this context about the “p1” object.

On the terminal screen below, the output is printed.

Example # 4: Using the “Run” Scope Function in Kotlin

The ‘run’ function is identical to the ‘let’ and ‘with’ functions. When the object lambda comprises both object initialization and returns value processing, then the “run” function is useful.

In the above code, we have a class called “Teachers” in which we have defined variables as “name”, “phone” and “subject”. Then in the main function, we have an object as “teacher” that uses the apply function. Note that we have not used an object name to refer to the class members and initialize them with the values. After that, we have invoked the run function which is known as a non-extension run function because no receiver object is passed to it.

The output of the non-extension run function is shown in the below image.

Example # 5: Using the “Also” Scope Function in Kotlin

The “also” function is comparable to the “let” function except that it refers to the object’s context as “it” rather than “this” and provides null safety checks.

In the above code, we have a main function in which we declare a variable as “val” with the name “myList”. The variable “myList” contains the list of values by using the mutableListOf function. We have called the “also” function for the “myList” variable. In the “also” block, we have used the “it” keyword with the add function and passed a value to it. Then, we have to again use the “it” keyword with the remove function and pass a value that we want to remove. Through the println function, we will see the updated list values.

The output below shows that the list has been updated.

Conclusion

We’ve gone over the scope functions in great depth based on the prior example’s demonstrated outcomes. All of these illustrations are simple and run on Ubuntu 20.04, and they will assist you in learning how to use the scope functions.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.