Complete the code to use the apply function to initialize the object.
val person = Person().[1] { name = "Alice" age = 30 }
The apply function allows you to configure an object within its scope and returns the object itself.
Complete the code to print the object's properties using apply.
val car = Car().[1] { brand = "Toyota" year = 2020 println("Brand: $brand, Year: $year") }
apply lets you configure the object and run code inside its scope using this. Here, it prints properties after setting them.
Fix the error in the code by choosing the correct function to initialize and return the object.
val book = Book().[1] { title = "Kotlin Guide" pages = 250 } println(book.title)
apply returns the object after applying changes, so book holds the initialized object.
Fill both blanks to create a mutable list and add elements using apply.
val numbers = mutableListOf<Int>()[1] { add(1) add(2) add(3) }[2] println(numbers)
Using apply both times lets you add elements inside the block and returns the list itself for printing.
Fill all three blanks to create a data class instance, configure it with apply, and print its properties.
data class User(var username: String = "", var email: String = "") val user = User()[1] { username = "john_doe" email = "john@example.com" } println("Username: ${user.[2], Email: ${user.[3]")
apply is used to configure the User object. Then, the properties username and email are accessed to print their values.