🐦 Kotlin Beginner

What does the run scope function do in Kotlin?

Answer

The run scope function executes a block where this is the object and returns the result of the block — it combines the object access of apply with the return value of let. Example: val result = user.run { "${name} is ${age} years old" }. It is also usable as a non-extension function: val result = run { val x = compute(); x * x }, which is useful for creating a local scope for computation without creating a dedicated function. Use run when you need both object access and want to return a transformed value.