https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

phldavies

08/10/2022, 9:19 AM
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

Klitos Kyriacou

08/10/2022, 9:40 AM
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

Rick Clephas

08/10/2022, 12:23 PM
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

Ubi

08/10/2022, 2:30 PM
If x is a
val
then it is does not matter but if x is a
var
then use
x?.let{}
.
☝🏻 1
☝️ 1
a

Alex Cruise

08/10/2022, 3:03 PM
I like not having to name intermediate values so I generally prefer
?.let
j

Jacob

08/11/2022, 2:38 AM
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
2 Views