apply
The Kotlin scope function apply is used to configure or initialize an object. Inside the block, you reference the object via this, and the return value is the receiver itself.
Syntax
// Basic form of apply
val result = object.apply {
// this = the object
property = value
method()
}
// result is the object itself
Scope Functions Overview
| Scope Function | Context Reference | Return Value | Use Case |
|---|---|---|---|
| apply { } | this (can be omitted) | Receiver itself | Used to configure or initialize an object. |
| also { } | it | Receiver itself | Used to insert side effects such as logging or debugging. |
| let { } | it | Lambda result | Used for null checks or transformation chains. |
| run { } | this (can be omitted) | Lambda result | Combines object setup with a computation. |
Sample Code
data class Person(var name: String = "", var age: Int = 0, var email: String = "")
fun main() {
// Initialize an object with apply (this can be omitted).
val person = Person().apply {
name = "Alice"
age = 30
email = "alice@example.com"
}
println(person)
// Person(name=Alice, age=30, email=alice@example.com)
// apply is also commonly used to build a StringBuilder.
val sb = StringBuilder().apply {
append("Hello")
append(", ")
append("Kotlin!")
}
println(sb.toString()) // Hello, Kotlin!
// apply chaining — you can chain multiple configurations together.
val list = mutableListOf<String>().apply {
add("Apple")
add("Banana")
add("Cherry")
}
println(list) // [Apple, Banana, Cherry]
// Because apply returns the receiver, you can call another method on it directly.
val size = mutableListOf<Int>().apply {
addAll(listOf(1, 2, 3, 4, 5))
}.size
println(size) // 5
}
Notes
apply is commonly used as an initialization block for an object. Inside the block, the receiver is referenced via this, so you can assign to properties directly by name.
Because the return value is the receiver itself, it is convenient to assign the newly created object directly to a variable or use it as part of a method chain.
For inserting side effects, see also. For null checks, see let. When you need to return a computed result, see run / with.
If you find any errors or copyright issues, please contact us.