The 'run' function in Kotlin is a powerful extension function that can be used for executing a block of code within a specific context. This is particularly useful when you want to execute multiple operations on an object and return a result. It combines the capabilities of 'let' and 'with', allowing you to access the object directly without needing to repeat its name. This can make your code cleaner and more readable.
data class User(val name: String, val age: Int)
fun main() {
val user = User("Alice", 30)
val userInfo = user.run {
"Name: $name, Age: $age"
}
println(userInfo) // Output: Name: Alice, Age: 30
}