I’m surprised there’s no guidance on when to prefe...
# getting-started
p
I’m surprised there’s no guidance on when to prefer
x?.let { ... }
to
if (x != null) { … }
in the coding conventions. Am I right in thinking the preference of
?.let
would be when the result is used as an expression, but
if (!= null)
is better served for control-flow?
👍 1
k
I also have a general personal guidance of "prefer whichever one reads better". In this particular case, I agree with what you said, but I also sometimes use
Copy code
(very + complicated() * expression)?. let { ... }
instead of
Copy code
val x = (very + complicated() * expression)
if (x != null) { ... }
Because unfortunately you can't do this (something that can be done e.g. in C++):
Copy code
if ((val x = ...) != null) { doSomethingWith(x) }
r
I also have a general personal guidance of “prefer whichever one reads better”.
That’s mostly what I do as well. You can actually do something like that with a `when`:
Copy code
when (val x = a) {
    null -> { println("x is null") }
    else -> { doSomethingWith(x) }
}
u
If x is a
val
then it is does not matter but if x is a
var
then use
x?.let{}
.
☝🏻 1
☝️ 1
a
I like not having to name intermediate values so I generally prefer
?.let
j
if your not going to use x with the let block ie
x?.let{doSomethingWithoutX()}
then you'd be better off just doing an if