Using the 'with' Scope Function for Contextual Execution

The 'with' scope function in Kotlin is a powerful tool that allows you to execute multiple operations on an object without repeating its name. This can lead to cleaner and more readable code, especially when you're working with an object that requires several modifications or property accesses. It is ideal when you want to work with a specific object for a short block of code.


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

fun updateUser(user: User) {
    with(user) {
        name = "Alice"
        age += 1
    }
}

fun main() {
    val user = User("Bob", 25)
    updateUser(user)
    println(user) // Output: User(name=Alice, age=26)
}