What if you could set up an object's properties all at once, without repeating its name every time?
Why Apply function behavior and use cases in Kotlin? - Purpose & Use Cases
Imagine you want to create and configure an object in Kotlin, like setting multiple properties one by one after creating it.
You write code like this:
val person = Person()
person.name = "Alice"
person.age = 30
person.city = "Paris"
This feels repetitive and clunky, especially when you have many properties to set.
Manually setting each property takes many lines and can clutter your code.
It's easy to forget to set a property or make mistakes when repeating similar lines.
This slows down coding and makes your code harder to read and maintain.
The apply function lets you create and configure an object in one clean block.
Inside the apply block, you can set properties directly on the object without repeating its name.
This makes your code shorter, clearer, and less error-prone.
val person = Person() person.name = "Alice" person.age = 30 person.city = "Paris"
val person = Person().apply {
name = "Alice"
age = 30
city = "Paris"
}You can build and configure objects quickly and clearly, making your code easier to write and understand.
When creating a user profile in an app, you can use apply to set all user details in one place, improving readability and reducing mistakes.
apply helps configure objects in a neat block.
It reduces repetitive code and errors.
It makes your Kotlin code cleaner and easier to maintain.
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
