Skip to content

Using Kotlin's 'also'

Kotlin, Programming, Development1 min read

If you're a Kotlin developer, you might have come across the 'also' function. The 'also' function is a part of the standard library in Kotlin and it can be used to perform some additional actions on an object within a chain of method calls.

The syntax for using 'also' is straightforward. It takes an object as an argument and a lambda expression that specifies the additional actions that need to be performed on the object. Here's an example:

1val text = "Hello World"
2text.also {
3 println("String length : ${it.length}")

In this example, we are creating a string called 'text' with the value "Hello World". We then call the 'also' function on the 'text' object, which takes a lambda expression that prints the length of the string to the console. The 'also' function also returns the original object, which allows us to chain further method calls on to it. In this case, we are calling the 'uppercase()' function on the 'text' object to convert the string to uppercase.

Let's take a look at some examples of how 'also' can be used in Android development.

Example 1: Initializing Views

When working with views in Android, we often need to set some properties such as text, visibility, or onClickListener. We can use the 'also' function to initialize views and set their properties in a concise and readable way.

1val textView = TextView(context).also {
2 it.text = "Hello World"
3 it.visibility = View.VISIBLE
4 it.setOnClickListener { view ->
5 // Handle click event here
6 }

In this example, we are creating a new 'TextView' object and initializing its properties within the 'also' block. This allows us to write more readable code and reduces the number of lines we need to write.

Example 2: Logging Method Calls

We can also use 'also' to log method calls on an object. This can be useful when debugging our application.

1fun fetchData() {
2 val url = ""
3 val response = URL(url).openStream().bufferedReader().use { it.readText() }
4 Log.d(TAG, "Fetched data : $response")
7fetchData().also {
8 Log.d(TAG, "Data fetched at : ${Date()}")

In this example, we have a 'fetchData()' function that fetches data from a web API. We call the function and then use 'also' to log the time at which the data was fetched. This can be useful when trying to identify performance issues or debugging network-related problems.

Overall, the 'also' function is a powerful tool that can help us write more concise and readable code. By allowing us to perform additional actions on an object within a chain of method calls, we can reduce the amount of boilerplate code we need to write while still maintaining readability.