The apply function helps you set up or change an object easily by running code inside it. It makes your code shorter and clearer.
0
0
Apply function behavior and use cases in Kotlin
Introduction
When you want to create an object and set many properties at once.
When you want to configure an object right after creating it.
When you want to run multiple commands on the same object without repeating its name.
When you want to improve code readability by grouping related changes.
When you want to return the object itself after applying changes.
Syntax
Kotlin
val result = obj.apply { // code to configure obj property1 = value1 methodCall() }
The apply function runs the block with this as the object.
It returns the original object after running the block.
Examples
Create a
Person and set name and age inside apply.Kotlin
val person = Person().apply { name = "Alice" age = 30 }
Create a list and add items inside
apply without repeating the list name.Kotlin
val list = mutableListOf<Int>().apply { add(1) add(2) add(3) }
Use
apply to build a string by appending parts step by step.Kotlin
val builder = StringBuilder().apply { append("Hello") append(" World") }
Sample Program
This program creates a Car object and sets its brand and year using apply. Then it prints the details.
Kotlin
data class Car(var brand: String = "", var year: Int = 0) fun main() { val myCar = Car().apply { brand = "Toyota" year = 2022 } println("Car brand: ${myCar.brand}") println("Car year: ${myCar.year}") }
OutputSuccess
Important Notes
apply is useful when you want to initialize or modify an object in one place.
Inside the apply block, you can access the object's properties and methods directly using this.
Because apply returns the object itself, you can chain calls or assign it immediately.
Summary
apply runs code on an object and returns the object itself.
It helps write cleaner and shorter code when setting up objects.
Use it to group changes to an object without repeating its name.