📖 Scenario: You are working on a Kotlin program that manages a simple user profile. You want to update the user's details in a clean and readable way using Kotlin's apply function.
🎯 Goal: Build a Kotlin program that creates a User data class instance and updates its properties using the apply function. Finally, print the updated user details.
📋 What You'll Learn
Create a User data class with name, age, and email properties
Create an instance of User with initial values
Use the apply function to update the name, age, and email properties
Print the updated User instance
💡 Why This Matters
🌍 Real World
Using <code>apply</code> helps write cleaner code when you want to initialize or update an object's properties without repeating the object name multiple times.
💼 Career
Understanding Kotlin scope functions like <code>apply</code> is important for Android development and Kotlin backend programming, making your code more readable and maintainable.
Progress0 / 4 steps
1
Create the User data class and an instance
Create a Kotlin data class called User with properties name (String), age (Int), and email (String). Then create a variable user of type User with initial values: "Alice" for name, 25 for age, and "alice@example.com" for email.
Kotlin
Hint
Use data class User(var name: String, var age: Int, var email: String) to define the class. Then create val user = User("Alice", 25, "alice@example.com").
2
Add a variable for new user details
Create a variable called newName and set it to "Bob". Also create newAge set to 30 and newEmail set to "bob@example.com".
Kotlin
Hint
Define val newName = "Bob", val newAge = 30, and val newEmail = "bob@example.com".
3
Use apply to update user properties
Use the apply function on the user object to update its name to newName, age to newAge, and email to newEmail. Assign the result back to a variable called updatedUser.
Kotlin
Hint
Use val updatedUser = user.apply { name = newName; age = newAge; email = newEmail } to update the user.
4
Print the updated user details
Write a println statement to print the updatedUser object.
Kotlin
Hint
Use println(updatedUser) to display the updated user details.
Practice
(1/5)
1. What does the apply function do in Kotlin?
easy
A. Runs code on an object and returns the same object
B. Creates a new object and returns it
C. Runs code and returns the last expression result
D. Runs code without returning anything
Solution
Step 1: Understand the purpose of apply
The apply function executes a block of code on the object it is called on.
Step 2: Identify the return value of apply
It always returns the original object after applying the block, not a new value.
Final Answer:
Runs code on an object and returns the same object -> Option A
Quick Check:
apply returns the object itself [OK]
Hint: Remember: apply returns the original object after changes [OK]
Common Mistakes:
Thinking apply returns the last expression result
Confusing apply with let or run
Assuming apply creates a new object
2. Which of the following is the correct syntax to use apply on an object person to set its name property to "Alice"?
easy
A. person.apply { name = "Alice" }
B. apply(person) { name = "Alice" }
C. person.apply(name = "Alice")
D. person.apply { setName("Alice") }
Solution
Step 1: Identify the correct lambda syntax for apply
apply takes a lambda with receiver where this is the object, so properties can be set directly.
Step 2: Check each option's syntax
person.apply { name = "Alice" } correctly uses person.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 A
Quick Check:
Use object.apply { property = value } syntax [OK]
Hint: Use curly braces with apply to set properties inside [OK]
Common Mistakes:
Passing parameters directly to apply
Using parentheses instead of curly braces
Calling non-existent setter methods
3. What is the output of this Kotlin code?
val list = mutableListOf<Int>().apply {
add(1)
add(2)
add(3)
}
println(list)
medium
A. Compilation error
B. []
C. null
D. [1, 2, 3]
Solution
Step 1: Understand what apply does on the list
The apply block adds 1, 2, and 3 to the mutable list.
Step 2: Check the returned value of apply
apply returns the original list after adding the elements, so list contains [1, 2, 3].
Final Answer:
[1, 2, 3] -> Option D
Quick Check:
apply adds elements and returns the list [OK]
Hint: apply returns the object after running code inside [OK]
Common Mistakes:
Expecting apply to return last added element
Thinking list is empty after apply
Confusing apply with run or let
4. Identify the error in this Kotlin code using apply:
The apply block correctly adds two entries to the map.
Step 2: Understand the map.get("c") call
Since key "c" does not exist, get returns null, which is printed without error.
Final Answer:
No error; output is null -> Option C
Quick Check:
Accessing missing key returns null, no error [OK]
Hint: Missing keys in map.get return null, no crash [OK]
Common Mistakes:
Expecting runtime error for missing key
Thinking apply must return a value explicitly
Confusing map access syntax
5. You want to create and configure a StringBuilder in Kotlin to build the string "Hello World!" using apply. Which code snippet correctly does this?
hard
A. val result = StringBuilder().apply { append("Hello"); append(" World!") }
B. val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString()
C. val result = StringBuilder().apply { append("Hello World!") }
D. val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString
Solution
Step 1: Understand apply returns the object itself
The apply block configures the StringBuilder, 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() calls toString() after apply, returning the built string. val result = StringBuilder().apply { append("Hello World!") } returns the StringBuilder object, not the string. val result = StringBuilder().apply { append("Hello"); append(" World!") } misses toString(). val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString misses parentheses on toString, causing error.
Final Answer:
val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString() -> Option B
Quick Check:
Call toString() after apply to get string [OK]
Hint: Call toString() after apply to get final string [OK]
Common Mistakes:
Forgetting to call toString() after apply
Missing parentheses on toString
Expecting apply to return string automatically
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.