Skip to main content
St Louis

Back to all posts

How to Use the "Apply" Function In Kotlin?

Published on
7 min read
How to Use the "Apply" Function In Kotlin? image

Best Kotlin Programming Tools to Buy in October 2025

1 Thriving in Android Development Using Kotlin: A project-based guide to using the latest Android features for developing production-grade apps

Thriving in Android Development Using Kotlin: A project-based guide to using the latest Android features for developing production-grade apps

BUY & SAVE
$38.49 $44.99
Save 14%
Thriving in Android Development Using Kotlin: A project-based guide to using the latest Android features for developing production-grade apps
2 Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

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

BUY & SAVE
$47.99
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)
3 Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

BUY & SAVE
$59.30 $89.99
Save 34%
Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin
4 Android UI Development with Jetpack Compose: Bring declarative and native UI to life quickly and easily on Android using Jetpack Compose and Kotlin

Android UI Development with Jetpack Compose: Bring declarative and native UI to life quickly and easily on Android using Jetpack Compose and Kotlin

BUY & SAVE
$36.26
Android UI Development with Jetpack Compose: Bring declarative and native UI to life quickly and easily on Android using Jetpack Compose and Kotlin
5 Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

BUY & SAVE
$45.60
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines
6 Reactive Programming in Kotlin: Design and build non-blocking, asynchronous Kotlin applications with RXKotlin, Reactor-Kotlin, Android, and Spring

Reactive Programming in Kotlin: Design and build non-blocking, asynchronous Kotlin applications with RXKotlin, Reactor-Kotlin, Android, and Spring

BUY & SAVE
$46.57 $48.99
Save 5%
Reactive Programming in Kotlin: Design and build non-blocking, asynchronous Kotlin applications with RXKotlin, Reactor-Kotlin, Android, and Spring
7 Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

BUY & SAVE
$36.99 $49.99
Save 26%
Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose
8 Kotlin - Server-Side Application Development, Programming v1 T-Shirt

Kotlin - Server-Side Application Development, Programming v1 T-Shirt

  • WRITE CONCISE CODE WITH KOTLIN'S POWERFUL TYPE INFERENCE FEATURE.
  • SEAMLESS JAVA INTEROPERABILITY ENHANCES VERSATILITY AND PRODUCTIVITY.
  • ENJOY A COMFORTABLE, LIGHTWEIGHT FIT WITH CLASSIC DOUBLE-NEEDLE DESIGN.
BUY & SAVE
$19.99
Kotlin - Server-Side Application Development, Programming v1 T-Shirt
9 Competitive Programming 4 - Book 2: The Lower Bound of Programming Contests in the 2020s

Competitive Programming 4 - Book 2: The Lower Bound of Programming Contests in the 2020s

BUY & SAVE
$24.00
Competitive Programming 4 - Book 2: The Lower Bound of Programming Contests in the 2020s
10 PC Building Tool Kit 140-IN-1: Computer Tool Kit for Repair & Assembly, Precision Screwdriver Set with Magnetic Bits for Laptop, iPhone, MacBook, PS4/5, Xbox, Game Console

PC Building Tool Kit 140-IN-1: Computer Tool Kit for Repair & Assembly, Precision Screwdriver Set with Magnetic Bits for Laptop, iPhone, MacBook, PS4/5, Xbox, Game Console

  • 120 PRECISION TOOLS FOR ANY REPAIR JOB-PERFECT FOR PROS & DIYERS!

  • VERSATILE CRV STEEL BITS-HANDLES ALL ELECTRONICS WITH EASE!

  • ERGONOMIC DESIGN & MAGNETIC TOOLS-ULTIMATE CONVENIENCE FOR REPAIRS!

BUY & SAVE
$19.99
PC Building Tool Kit 140-IN-1: Computer Tool Kit for Repair & Assembly, Precision Screwdriver Set with Magnetic Bits for Laptop, iPhone, MacBook, PS4/5, Xbox, Game Console
+
ONE MORE?

The "apply" function in Kotlin is a higher-order function that allows you to modify an object by applying a set of operations to it. It is often used for configuring an object after its initialization or for creating a fluent interface.

To use the "apply" function, you first select the object you want to modify and follow it with the "apply" function call using the dot notation. Inside the "apply" block, you can make changes to the properties or call methods of the object.

Here's an example that demonstrates the usage of the "apply" function:

class Person { var name: String = "" var age: Int = 0 var city: String = "" }

fun main() { val person = Person().apply { name = "John" age = 25 city = "New York" }

println(person.name) // Output: John
println(person.age) // Output: 25
println(person.city) // Output: New York

}

In the above example, we create a new instance of the Person class using the default constructor. Then, we apply a set of operations to the person object within the "apply" block. Finally, we can access the modified properties of the person object outside the "apply" block.

The "apply" function returns the object itself after the modifications have been applied. This allows you to chain multiple operations or method calls using the dot notation in a concise and readable way.

Overall, the "apply" function is useful when you want to configure or modify an object easily and fluently without the need for temporary variables. It is a convenient way to initialize and customize objects in Kotlin.

What is the syntax for using the "apply" function in Kotlin?

In Kotlin, the apply function is a scoping function that allows you to modify an object within a lambda expression. It returns the object itself after applying the lambda to it.

The syntax for using the apply function is as follows:

object.apply { // modify properties and call methods of the object }

Here's an example to illustrate its usage:

data class Person(var name: String, var age: Int)

val person = Person("John Doe", 25).apply { name = "Jane Smith" age += 1 }

In this example, the apply function is used on a Person object. Within the lambda block, you can modify properties or call methods of the object. After modifying the name and incrementing age, the modified person object is returned and assigned to the person variable.

This allows for a more concise and fluent way of modifying object properties.

What is the difference between "apply" and "also" functions in Kotlin?

In Kotlin, both apply and also are higher-order functions that can be used to manipulate objects. However, they have slightly different use cases and behavior:

  1. apply: This function is used when you want to apply a series of operations or changes to an object in a builder-like manner. It returns the original object after applying the changes. The block of code inside apply is executed as a lambda expression, and within that block, the object is referred to as this or it. Example:

val person = Person().apply { name = "John" age = 25 }

In the above code, apply is used to apply the name and age properties to a Person object.

  1. also: This function is used when you want to perform some additional actions on an object and don't need to modify the object itself. It returns the original object after performing the actions. The block of code inside also is executed as a lambda expression, and within that block, the object is referred to as it. Example:

val number = 10

number.also { println("The number is $it") }

In the above code, also is used to print the value of number without modifying it.

So, the main difference is that apply is used for modifying an object, while also is used for performing additional actions on an object without modification.

How does the "apply" function differ from other function scopes in Kotlin?

The "apply" function in Kotlin is a higher-order function that executes a block of code and returns the object it was called on. It is commonly used to initialize properties and call functions on an object after its construction.

The "apply" function differs from other function scopes in Kotlin, such as "let", "run", "also", and "with", in the following ways:

  1. Return value: The "apply" function always returns the object it was called on, while other function scopes may return the result of the lambda expression or other values.
  2. Receiver: The "apply" function provides a receiver object as the context for the lambda expression, allowing you to refer to the properties and functions of the object using the "this" keyword inside the lambda. Other function scopes may not provide a receiver object or use different keywords like "it" or "run" to refer to the receiver.
  3. Usage: The "apply" function is commonly used for initializing properties or calling multiple functions on an object shortly after its creation. Other function scopes may have different use cases, such as transforming the object, performing null checks, or executing a block of code with a specific context.

Overall, the "apply" function is useful when you want to perform multiple operations or set multiple properties on an object without assigning it to a variable. It provides a concise and readable way to configure objects and initialize their properties.

How to use the "apply" function with lambda expressions?

To use the "apply" function with lambda expressions in Python, you can follow these steps:

Step 1: Import the necessary libraries

import pandas as pd

Step 2: Create a DataFrame

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})

Step 3: Define the lambda expression

my_lambda = lambda x: x * 2

Step 4: Apply the lambda expression to a column using the "apply" function

df['col1'] = df['col1'].apply(my_lambda)

In the above example, the lambda expression defined as my_lambda = lambda x: x * 2 multiplies each value in the 'col1' column by 2. The "apply" function is then used to apply this lambda expression to each value in the 'col1' column, and the updated values are assigned back to the 'col1' column.

You can modify the lambda expression to suit your needs. The "apply" function can be used with lambda expressions to perform various operations on DataFrame columns, such as filtering, transforming, or creating new columns based on existing values.

What are some common use cases for the "apply" function?

The "apply" function in programming is commonly used when working with data frames or matrices in order to apply a specific function to every row or column. Some common use cases for the "apply" function are:

  1. Summarizing data: It can be used to calculate summary statistics such as the mean, median, or standard deviation for each row or column.
  2. Data transformation: "apply" can be used to transform the data in a specific way, such as converting all values to percentages, scaling the data, or applying a logarithmic transformation.
  3. Missing value imputation: "apply" can be used to replace missing values with a specific value, such as filling missing values with the mean or median of the respective column or row.
  4. Categorical data encoding: "apply" can be utilized to encode categorical variables into numerical values. For example, converting categorical variables like "male" and "female" to binary values like 0 and 1.
  5. Data filtering: It can be used to filter rows or columns based on a specific condition using a custom function.
  6. Data validation: "apply" can help in validating data by applying custom checks to each row or column and flagging any invalid or incorrect values.

Overall, the "apply" function provides a flexible and efficient way to perform various operations on data frames or matrices in a row-wise or column-wise manner.