Let vs run when it comes to check null
Solution 1:
You said it : the difference comes from "this" and "it" !
Everybody uses let
for a good reason : run
should be used when you want to return something, just like let
, where apply
or also
return the object it was called on.
But then, what is the difference between run
and let
? Well, run
should be used when you treat mostly the object as a receiver, on which you want to call a bunch of methods : as this
can be used implicitely, it's faster to write and easier to read.
But when the object is used as a value, then let
is preferable, because the value is named it
, which is shorter to use as a value (2 letters instead of 4), but more importantly, it is more readable ! Try reading :
myComputationThatMightReturnNull()?.let { it * 2 }
and
myComputationThatMightReturnNull()?.run { this * 2 }
The first one sounds more like spoken english, where the second is longer and more difficult to understand.
Because often the nullable value is used as... a value when it isn't null
, let is most likely to be used in this case than run. But don't be afraid to use the latter when it seems right to you to do so, it's just a rule of thumb.