Kotlin

Examples on the Usage of Kotlin “Also” Functions

The Kotlin programming language has a useful function which is known as the “also” function. Subsequently, it is an extension method that may be employed on any object and performs extra actions on it inside of a code block. Its goal is to provide you with the option of running some code on an object while still retaining the original object as the expression’s result.

When you wish to have an object that have certain side effects without changing its state, such as logging or troubleshooting the data, that use case is also rather popular. You can go on working with the original object or pass it unchanged to the other functions because it is returned as is. In this article today, we will confer the uses of the “also” function in Kotlin with the assistance of some code illustrations.

Syntax:

Before moving toward the code examples, let’s take a look at the syntax of Kotlin’s “also” function that is provided as follows:

object.also { lambda-expression }
  • object: It denotes the object on which the “also” function is called. It could be any entity of any kind.
  • also: It is the title of the function which the object calls. The Kotlin standard library has an extension method for it.
  • { lambda }: It is a lambda expression that is enclosed in curly braces that serve as an argument to the “also” function. You can write the code that performs additional operations within lambda.

While employing the “also” function, you may manipulate the object in any way since you supply a lambda function as a parameter. Once the lambda is executed, the “also” method yields the original object which enables you to connect to additional operations.

Example 1:

Let’s begin with the very first code example of Kotlin that creates an initially empty mutable list and, using the “also” function, adds three integers (2, 5, and 3) to the list. In the main function, a mutable “L” list of integers is created using the mutableListOf<Int>() function. The “also” method is called on the “L” list.

The purpose of this is to perform additional operations on the list within a lambda scope while still keeping the original list intact. The lambda expression is represented by { }. Within lambda, three elements are added to the list using the add function: it.add(2) adds the integer 2 to the list, it.add(5) adds the integer 5 to the list, and it.add(3) adds the integer 3 to the list. The “also” function returns the original “L” list after the operations in lambda are executed.

The “map” method is then invoked on the returned list. Using the lambda { it * 3 } expression, it is utilized to multiply each element of the list by 3 which results in a new list. The new list is stored in the “Res” variable, and its contents are printed using println(Res).

fun main() {

val L = mutableListOf<Int>()

val Res = L.also {

it.add(2)

it.add(5)

it.add(3)

}.map { it * 3 }

println(Res)

}

Finally, the output of the “Res” variable is shown in the following console:

Example 2:

Let’s use the “also” function in Kotlin code to perform other operations at the same time like converting from lowercase to uppercase. The “str” variable is declared with a “Bryan” value using the “val” keyword.

Now, we apply the “also” function to the “str” variable using the “str.also” expression. The “also” function takes a lambda expression as an argument. The println is the lambda expression that is passed to the “also” function. Within lambda, the “it” parameter represents the original value of “str”.

Here, the lambda prints the “String before:” string followed by the value of it (which is “Bryan”). The toUpperCase() function is called on the result of the “also” method. It converts the string to the uppercase. Now, the “also” function is applied to the output of the toUpperCase() method.

Another “also” function call allows further operations within a lambda. Now, the println(“String after Also: $it”) is the second lambda expression that is passed to the second “also” function. Again, it represents the modified value of the string (uppercase “BRYAN”). The lambda prints “String after Also:” followed by its value of it.

fun main() {

val str = "Bryan"

str.also {

println("String before: $it")

}.toUpperCase().also {

println("String after Also: $it")

}}

The execution of the program is complete, and the output is shown on the console. The output of the code displays the before and after strings to the console:

Example 3:

Let’s have the last example of this article using the “also” function. We define a “main” function and a data class named “Dummy” with three properties: name of type String, distance of type Int, and place of type String. The “Data” classes are used to hold the data and automatically generates useful methods like equals, hashCode, and toString.

We create an instance of the “Dummy” class named “info” with the values of “Alice” for name, 2450 for distance, and “New York” for place. We use the “also” function on the “Info” object. Within the lambda expression, we refer to the object as it is.

We modify the properties of the “Dummy” object inside lambda. Specifically, we increment the “Distance” property by 540 (resulting in 2990) and change the value of the “Place” property to “Italy”. The “also” function returns the modified info object which we assign to a new variable named “Data”. Finally, we use “println” to print the value of the “Data” object which calls the “toString” method of the “Dummy” class and display its contents.

fun main() {

data class Dummy(val Name: String, var Distance: Int, var Place: String)

val info = Dummy("Alice", 2450, "New York")

val Data = info.also {

it.Distance += 540

it.Place = "Italy"

}

println(Data)

}

The output displays the updated values of the “Name”, “Distance”, and “Place” properties of the “Dummy” object after applying the modifications inside the “also” lambda as shown in the following:

Conclusion

The article discusses the usage of the “also” function in Kotlin with the help of code examples. Its purpose is to enable the running code on an object while preserving the original object as the result of the expression. The syntax of the “also” method involves calling it on an object, followed by a lambda expression inside the curly braces. The lambda allows to perform the additional operations on the object. Each example demonstrates the ability to perform the additional operations on an object using the “also” function while preserving the original object and its state.

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.