apply function. What will be printed when this code runs?data class Person(var name: String, var age: Int) fun main() { val person = Person("Alice", 25).apply { name = "Bob" age += 5 } println(person) }
apply runs the block on the object and returns the object itself.The apply function executes the block with this as the object, allowing you to modify its properties. It returns the object itself after modifications. Here, name is changed to "Bob" and age is increased by 5, so the final object is Person(name=Bob, age=30).
apply function works in Kotlin.this refers to inside the block and what the function returns.The apply function runs the block with this as the object, allowing direct access to its members, and returns the object itself after the block finishes.
class Box(var content: String?) fun main() { val box: Box? = Box(null) box?.apply { content = content!!.uppercase() } println(box?.content) }
!! operator inside the apply block.The apply block runs only if box is not null due to the safe call ?.. However, inside the block, content is null, and the !! operator forces a non-null assertion, causing a NullPointerException.
apply to add elements to a mutable list and returns the list.apply returns the object itself automatically after the block.Option B correctly uses apply to add elements to the list. The apply function returns the object itself, so no explicit return is needed. Option B and D have invalid return statements inside the lambda, causing syntax errors. Option B uses a labeled return which is unnecessary here and can cause confusion.
val list = mutableListOf<String>().apply { add("a") add("b") }.apply { add("c") remove("a") }.apply { add("d") clear() add("e") } println(list.size)
The list starts empty. First apply adds "a" and "b" (list: ["a", "b"]). Second apply adds "c" and removes "a" (list: ["b", "c"]). Third apply adds "d", clears the list, then adds "e" (list: ["e"]). So the final list has 1 element.