How to Use the "Apply" And "Run" Extension Functions In Kotlin?

9 minutes read

The "apply" and "run" extension functions in Kotlin are useful for executing a block of code on an object and modifying its properties within that block. They eliminate the need to repeatedly reference the object's name and provide a concise way to configure and customize an object.


The "apply" function is primarily used for setting up an object. It takes an object as its receiver and executes the specified block of code on that object. It returns the object itself, allowing us to chain multiple function calls together. Inside the block, we can access and modify the object's properties directly without having to prepend the object name.


Example:

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


In the above example, the "apply" function is called on a newly created "Person" object. The block inside the "apply" function sets the name, age, and address of the person. The "apply" function returns the modified "person" object.


The "run" function is similar to "apply" but with a slight difference in its return value. It also takes an object as its receiver and executes the specified block of code. However, the "run" function returns the result of the last expression inside the block. It can be used for performing some calculations or accessing properties of the object.


Example:

1
2
3
4
5
val person = Person().run {
    name = "John"
    age = 25
    getAddress()
}


In the above example, the "run" function is called on a newly created "Person" object. The block inside the "run" function sets the name and age of the person and then retrieves the address using the "getAddress" function. The "run" function returns the address value retrieved from the object.


Both "apply" and "run" extension functions are powerful tools that help enhance the readability and conciseness of Kotlin code. They provide a convenient way to initialize and work with objects, making code more expressive and efficient.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.8 out of 5

Kotlin Cookbook: A Problem-Focused Approach

4
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.7 out of 5

Head First Kotlin: A Brain-Friendly Guide

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

Rating is 4.6 out of 5

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

6
Effective Kotlin: Best Practices (Kotlin for Developers Book 5)

Rating is 4.5 out of 5

Effective Kotlin: Best Practices (Kotlin for Developers Book 5)

7
Java to Kotlin: A Refactoring Guidebook

Rating is 4.4 out of 5

Java to Kotlin: A Refactoring Guidebook

8
Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing

Rating is 4.3 out of 5

Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing


What is the return value of the run function in Kotlin?

The return type of the run function in Kotlin is determined by the lambda expression passed to it. It returns the value of the last expression inside the lambda.


For example, consider the following code snippet:

1
2
3
4
5
val result = run {
    val a = 5
    val b = 10
    a + b
}


In this case, the run function evaluates the lambda expression and returns the value of a + b. Therefore, the value of result will be 15.


How to apply default values using the apply function?

To apply default values using the apply function in Python, you can use the lambda function along with the apply function to specify the default value for a specific column.


Here is an example:

1
2
3
4
5
6
7
8
9
import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# Apply function with default value
df['D'] = df['C'].apply(lambda x: x if pd.notna(x) else "Default Value")

print(df)


Output:

1
2
3
4
   A  B  C             D
0  1  4  7             7
1  2  5  8             8
2  3  6  9             9


In the example, the apply function is used to check each value in column C. If the value is not NaN, it will be kept as it is. Otherwise, it will be replaced with the default value "Default Value".


You can change the lambda function to suit your specific default value requirement.


How to apply multiple properties using the apply function?

To apply multiple properties using the apply function, you can follow these steps:

  1. Define a function that encapsulates the operations you want to apply to the data.
  2. Use the apply function along with the lambda function to apply the defined function to the desired axis (rows or columns) of the data.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import pandas as pd

# Sample data
data = {'Name': ['John', 'Emily', 'Ryan'],
        'Age': [25, 30, 35],
        'Salary': [50000, 60000, 70000]}

df = pd.DataFrame(data)

# Function to apply multiple properties
def multiply_salary_and_age(row):
    row['Age'] *= 2
    row['Salary'] *= 1.1
    return row

# Applying the function to the dataframe using the apply function
df = df.apply(lambda row: multiply_salary_and_age(row), axis=1)

# Print the resulting dataframe
print(df)


In this example, we define a function multiply_salary_and_age that takes a row of data and multiplies the 'Age' value by 2 and the 'Salary' value by 1.1. We then use the apply function with the lambda function to apply this function to each row of the dataframe df along the rows axis (axis=1). The resulting dataframe is printed, showing the modified values for 'Age' and 'Salary'.


How to use the run function to execute a block of code?

To use the run function to execute a block of code, you need to perform the following steps:

  1. Define the block of code you want to execute. This could be a single statement or multiple statements enclosed in curly braces ({ }).
  2. Call the run function and provide the block of code as an argument.


Here's an example:

1
2
3
4
5
6
7
8
9
fun main() {
    run {
        // code block to be executed
        println("Hello, world!")
        val x = 10
        val y = x * 2
        println("The value of y is $y")
    }
}


In this example, we have a block of code inside the run function. The code block prints "Hello, world!" to the console, performs some calculations, and prints the value of the variable y.


When you run the program, the code inside the run function will be executed. The output will be:

1
2
Hello, world!
The value of y is 20


Twitter LinkedIn Telegram Whatsapp

Related Posts:

In order to import an extension function in Kotlin, you need to define the function as an extension function in a separate file or within the same file where you plan to use it. The extension function should be defined with the receiver type specified before t...
Extension functions in Kotlin allow us to add new functions to existing classes without modifying their source code. This feature helps to keep the codebase clean and enables us to work with third-party libraries or system classes more efficiently.To define an...
In Kotlin, the "let" extension function is used to operate on nullable objects and safely perform operations on them within a code block. It works by passing the object reference as a parameter to the function block and executing the operations on the ...