One doesnt need to use 'run' -- any more then any ...
# android
d
One doesnt need to use 'run' -- any more then any other library function (run is not a builtin keyword its 'just a function') There are many cases where one might want to use 'run' or where something of similar semantics is needed . 'run' is a function with a 'receiver' , unlike a basic expression or a bare {} lambda. This allows it to be used in places where basic expressions or statements are not allowed or require 'wrapping' (such as with run!) You cannot do this: ('if' does not accept a receiver)
"hi".if( this == "bye" ) println( "BYE" ) else println( this )
But you can do this
"hi".run {
if( this == "bye" ) println( "BYE" ) else println( this )
}
Another common use case for run is as the body of a function that is more then 1 expressions so you can 'avoid' using return ..
fun  printAndAdd( a: Int )  : Int {
println(a)
return a+1
}
vs
fun printAndAdd( a: Int ) = run {
println(a)
a+1
}
Note: the later case allows the compiler to infer the return type as well as eliminate the return statement fairly minor difference in the above case but can be more useful as the body gets more complex.