Is there a difference between this piece of code:
fun isDogEating(): Boolean {
return dog?.let { return it.eating } ?: false
}
and this
fun isDogEating(): Boolean {
return dog?.eating ?: false
}
I bumped into something like the first and was wondering whether the let
is redundant here.
There are no differences in behavior.
Both functions return false
if dog == null
, because of the ?: false
at the end.
The let
function is only executed if dog != null
.
Same with the eating
property in the second example
Note that the return
statement in the let
lambda means to return from the isDogEating
function, not from the lambda! To return from the lambda one may use the return@let
or just the expression
I prefer a shorter version:
fun isDogEating() = dog?.eating ?: false