Is this syntax is correct, `model?.let{ some code}...
# announcements
m
Is this syntax is correct,
model?.let{ some code} ?: run { code in case model is null}
g
syntactically correct but IMO just wrong in terms of style, you probably looking for if/else:
Copy code
if (model != null) { some code } else { code in case model is null }
4
👍 4
t
@Mohamed Ibrahim when you start using kotlin it can be very tempting to use
let
and
?:
for cases where `if`/`else` are much better fits
i noticed this with myself and most people i've introduced to the language
👍 2
p
Also there is a slight difference between these two. Using `let`: code in
run
will be executed if
model
is `null`or if
some code
in
let
will return
null
.
g
some code
in
let
will return
null
true, which make it even more confusing
if it really matters I prefer this:
Copy code
val someResult = if (model != null) { some code } else null
if (someResult == null) {
 //code in case model or result is null
}
but usually try to separate checking for receiver nullability and expression result
s
I’m still on the “let for everything”-train 😆
🤣 1
j
Interesting! I’ve used
let
operator when data could have changed in runtime, and also compiler doesn’t allow to have an
if/else
, so that’d be a good idea IMO, use let operator when an
if/else
is not allowed.
r
I definitely agree with @Jessie on using
let
to wrap mutable variables. But it’s kind of unclear from the sample whether that’s happening.
😊 1
g
to wrap Mutable variables
Copy code
val immutable = mutable
r
I hate to have to instantiate a new variable just to do that..
Copy code
someMutable?.let {
  //lock state and do work
}
/*now I don't have another thing hanging around representing old state*/
g
It's really depends on case, of course, but usually local variable just more readable and has less nesting
👍 1