data class User(val name: String, val email: String, val age: Int)
fun main() {
val user = User("Alice", "a@x.com", 30)
// run with a receiver — compute a transformed value
val summary: String = user.run {
"$name <$email> ($age yrs)" // implicit `this.`
}
println(summary)
// run without a receiver — encapsulate temporary state
val factor = run {
val configured = System.getenv("SCALE_FACTOR")?.toIntOrNull()
configured ?: 1
}
println(factor)
// run for early return value computation
fun greet(name: String?): String = name?.run {
"Welcome back, $this!" // `this` is the non-null name
} ?: "Welcome, guest"
println(greet("Alice"))
println(greet(null))
}
Create a free account and build your private vault. Share publicly whenever you want.