Using the 'apply' Function for Object Configuration

The 'apply' function in Kotlin is a scope function that allows you to configure an object in a concise manner. It executes a block of code on the object it is called upon and returns the object itself. This is particularly useful for initializing objects with multiple properties, as it helps keep the code clean and reduces redundancy.

data class User(var name: String = "", var age: Int = 0)

fun main() {
    val user = User().apply {
        name = "Alice"
        age = 30
    }
    println(user) // Output: User(name=Alice, age=30)
}