How to Use apply Function in Kotlin: Simple Guide
In Kotlin, the
apply function is used to configure an object within a block and then return the object itself. It allows you to call multiple methods or set properties on the object without repeating its name, making your code cleaner and easier to read.Syntax
The apply function is called on an object and takes a lambda block where this refers to the object. Inside the block, you can access the object's properties and methods directly. The function returns the original object after applying the block.
- object.apply { ... }: Calls
applyon the object. - this: Refers to the object inside the lambda.
- Returns: The same object after the block executes.
kotlin
val obj = SomeClass().apply {
property1 = value1
methodCall()
}Example
This example shows how to create and configure a Person object using apply. It sets the name and age properties inside the apply block and then prints the object.
kotlin
data class Person(var name: String = "", var age: Int = 0) fun main() { val person = Person().apply { name = "Alice" age = 30 } println(person) }
Output
Person(name=Alice, age=30)
Common Pitfalls
A common mistake is confusing apply with let or run. Unlike let, which passes the object as it, apply uses this and returns the object itself, not the lambda result. Also, avoid using apply when you need to transform the object into another value.
Wrong usage example:
val length = "hello".apply {
println(this)
}
// length is String, not IntRight usage example:
val length = "hello".let {
println(it)
it.length
}
// length is IntKey Takeaways
Use
apply to configure an object and return it in a clean, readable way.apply uses this inside its block to refer to the object.It is best for initializing or setting up objects, not for transforming values.
Do not confuse
apply with let or run; they differ in scope and return value.Using
apply reduces repetitive code when setting multiple properties.