How to Use the 'Apply' And 'Also' Extension Functions In Kotlin?

10 minutes read

The apply and also extension functions in Kotlin are useful tools for modifying and configuring objects in a concise and readable way. Both functions allow you to specify a block of code to be executed on an object, but they differ in how they handle the return value.

  1. apply: The apply function is used to modify the properties of an object. It takes a lambda as its argument, where you can access the object using this keyword and make changes to its properties. The apply function returns the modified object itself.


Example:

1
2
3
4
5
val person = Person().apply {
    name = "John"
    age = 25
    setAddress("123 St, City")
}


  1. also: The also function is used to perform some additional operations on an object without modifying its properties. It takes a lambda as its argument, where you can access the object using it keyword and perform any additional operations. The also function returns the original object itself.


Example:

1
2
3
4
5
6
val person = Person()
person.also {
    it.name = "John"
    it.age = 25
    println("Additional operations on person object.")
}


Both functions allow for a more concise and readable way to configure and modify objects without the need for temporary variables. They are particularly useful when working with immutable objects or builder pattern.


Note: The examples above assume the existence of a Person class with properties like name, age, and a setter method setAddress().

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.9 out of 5

Kotlin Cookbook: A Problem-Focused Approach

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Rating is 4.6 out of 5

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

6
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.5 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

7
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.4 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

8
Java to Kotlin

Rating is 4.2 out of 5

Java to Kotlin

9
Kotlin Essentials (Kotlin for Developers)

Rating is 4.1 out of 5

Kotlin Essentials (Kotlin for Developers)


How to write clean and concise code using 'apply' and 'also' functions in Kotlin?

To write clean and concise code using the apply and also functions in Kotlin, you can follow the following guidelines:

  1. Use apply when you need to modify multiple properties of an object and explicitly return the modified object. val person = Person().apply { name = "John" age = 25 address = "123 Main Street" }
  2. Use also when you need to perform some additional operations on an object without modifying its properties and return the original object. val person = Person().also { println("Creating person") // Additional operations without modifying the object }
  3. Avoid nesting apply or also blocks excessively, as it can reduce code readability. Instead, separate them into separate lines or functions when necessary. val person = Person().apply { setupNameAndAge() setupAddress() } private fun Person.setupNameAndAge() { name = "John" age = 25 } private fun Person.setupAddress() { address = "123 Main Street" }
  4. Avoid using apply or also functions when a simple assignment or method call is sufficient and more readable. val person = Person().apply { name = "John" calculateAge() } // More readable alternative val person = Person().apply { name = "John" } person.calculateAge()


By following these guidelines, you can write clean and concise code using apply and also functions in Kotlin. Remember to prioritize readability and maintainability when deciding whether to use them.


What is the scope of variables inside the 'also' function in Kotlin?

The also function in Kotlin is an extension function used for scoping and performing additional actions on an object within a specified scope. It has a receiver object and a lambda function as parameters.


The scope of variables inside the also function is limited to the lambda block. Any variables declared within the lambda block can only be accessed inside that block and will not be visible outside of it. This is because the lambda block creates a separate scope for variables, allowing you to perform operations and access properties of the receiver object without affecting the outer scope.


Here's an example illustrating the scope of variables inside the also function:

1
2
3
4
5
6
7
8
9
val stringValue = "Hello"

val modifiedString = stringValue.also {
    val length = it.length // length variable only accessible inside the lambda block
    println("Length of string: $length")
    // Perform other operations using the receiver object
}.toUpperCase() // Can access the modified receiver object outside the lambda block

println("Modified string: $modifiedString")


In the above example, the length variable can only be accessed within the lambda block passed to also. However, the modified receiver object can be accessed outside the lambda block, as shown in the toUpperCase() function call.


How can 'apply' and 'also' functions improve Kotlin code readability?

The apply and also functions are Kotlin standard library functions that can improve code readability in different ways:

  1. apply function: The apply function allows you to define a scope in which you can modify the properties of an object. It takes a lambda function as an argument and returns the object itself after applying the modifications. This function is especially useful when initializing or configuring an object with multiple properties. It improves readability as it keeps the modification code separate from the object creation, making it easier to understand what modifications are being made. Additionally, it eliminates the need for temporary variables or intermediate steps.


Example:

1
2
3
4
5
val person = Person().apply {
    name = "John"
    age = 30
    address = "123 Main St"
}


  1. also function: The also function is similar to apply, but it does not modify the object itself. Instead, it allows you to perform additional actions on the object within a scope. It takes a lambda function as an argument and returns the object itself. This function improves readability by providing a clear way to perform additional operations while chaining method calls or modifying an object's properties.


Example:

1
2
3
4
val result = someObject.also {
    // perform additional actions on someObject
    log("Additional actions performed on $it")
}


In summary, apply and also functions improve Kotlin code readability by clearly separating configuration/modification code from object creation and providing a convenient way to perform additional operations within method chaining.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

The Kotlin Standard Library functions are a collection of commonly used extension functions and top-level functions provided by the Kotlin programming language. These functions aim to simplify and enhance the development process by offering a set of utility fu...
Working with Android extensions in Kotlin allows you to leverage the power of Kotlin's extension functions to easily enhance the functionality of Android classes. Here's how you can work with Android extensions in Kotlin.To create an Android extension,...
You can use map() inside an extension function in Kotlin to transform each item of a collection into another object and return a new collection. Here's how you can do it:Define an extension function on the Iterable interface or any of its subclasses, such ...
To use a Kotlin function in Java, you can follow these steps:Create a Kotlin function that you want to use in Java. For example, let's consider a simple function named printMessage() that prints a message. fun printMessage() { println("Hello, world...
Extension functions in Kotlin allow you to add new functionality to an existing class, even if you don't have access to its source code. This feature is particularly advantageous when working with classes from external libraries or Android framework classe...
To run Kotlin on Ubuntu, you can follow these steps:Install Java Development Kit (JDK): Since Kotlin runs on the Java Virtual Machine (JVM), you need to have Java installed on your system. Open a terminal and run the following command to install the default JD...