The apply function helps you set up or change an object easily by running code inside it. It makes your code shorter and clearer.
Apply function behavior and use cases in 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.
Person and set name and age inside apply.val person = Person().apply { name = "Alice" age = 30 }
apply without repeating the list name.val list = mutableListOf<Int>().apply { add(1) add(2) add(3) }
apply to build a string by appending parts step by step.val builder = StringBuilder().apply { append("Hello") append(" World") }
This program creates a Car object and sets its brand and year using apply. Then it prints the details.
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}") }
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.
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.
Practice
apply function do in Kotlin?Solution
Step 1: Understand the purpose of
Theapplyapplyfunction executes a block of code on the object it is called on.Step 2: Identify the return value of
It always returns the original object after applying the block, not a new value.applyFinal Answer:
Runs code on an object and returns the same object -> Option AQuick Check:
applyreturns the object itself [OK]
- Thinking apply returns the last expression result
- Confusing apply with let or run
- Assuming apply creates a new object
apply on an object person to set its name property to "Alice"?Solution
Step 1: Identify the correct lambda syntax for
applyapplytakes a lambda with receiver wherethisis the object, so properties can be set directly.Step 2: Check each option's syntax
person.apply { name = "Alice" } correctly usesperson.apply { name = "Alice" }. apply(person) { name = "Alice" } is invalid syntax. person.apply(name = "Alice") wrongly passes a parameter. person.apply { setName("Alice") } assumes a setter method which may not exist.Final Answer:
person.apply { name = "Alice" } -> Option AQuick Check:
Useobject.apply { property = value }syntax [OK]
- Passing parameters directly to apply
- Using parentheses instead of curly braces
- Calling non-existent setter methods
val list = mutableListOf<Int>().apply {
add(1)
add(2)
add(3)
}
println(list)Solution
Step 1: Understand what
Theapplydoes on the listapplyblock adds 1, 2, and 3 to the mutable list.Step 2: Check the returned value of
applyapplyreturns the original list after adding the elements, solistcontains [1, 2, 3].Final Answer:
[1, 2, 3] -> Option DQuick Check:
apply adds elements and returns the list [OK]
- Expecting apply to return last added element
- Thinking list is empty after apply
- Confusing apply with run or let
apply:
val map = mutableMapOf()
map.apply {
put("a", 1)
put("b", 2)
}
println(map.get("c"))Solution
Step 1: Check the apply block usage
Theapplyblock correctly adds two entries to the map.Step 2: Understand the map.get("c") call
Since key "c" does not exist,getreturns null, which is printed without error.Final Answer:
No error; output is null -> Option CQuick Check:
Accessing missing key returns null, no error [OK]
- Expecting runtime error for missing key
- Thinking apply must return a value explicitly
- Confusing map access syntax
StringBuilder in Kotlin to build the string "Hello World!" using apply. Which code snippet correctly does this?Solution
Step 1: Understand
Theapplyreturns the object itselfapplyblock configures theStringBuilder, but to get the string,toString()must be called after.Step 2: Check each option's correctness
val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString() callstoString()afterapply, returning the built string. val result = StringBuilder().apply { append("Hello World!") } returns theStringBuilderobject, not the string. val result = StringBuilder().apply { append("Hello"); append(" World!") } missestoString(). val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString misses parentheses ontoString, causing error.Final Answer:
val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString() -> Option BQuick Check:
CalltoString()after apply to get string [OK]
- Forgetting to call toString() after apply
- Missing parentheses on toString
- Expecting apply to return string automatically
Ready to prove it?
Pass the test and this pattern moves unknown
