What do you find easier to read: ``` completedAler...
# codereview
d
What do you find easier to read:
Copy code
completedAlert?.let { updatedAlerts += it }
// or
if (completedAlert != null) updatedAlerts += completedAlert
2️⃣ 5
1️⃣ 12
s
as a kotlin noob, and java old fogey, I don't see ?.let {} as ever being easier to read than "if not null do something". i like the syntax of it, but "let" means nothing to me. Or maybe if someone described it better to me, otherwise everytime i encounter these types of things i have to stop and think about what that is actually doing and why. It'd be nice to have a
notNull
that was functionally the same as let, but that would at least describe what is going on.
c
the ? already means not null
s
i know. it just... doesn't read well to me for whatever reason
c
also possible:
updatedAlerts+=(completedAlert ?: 0)
h
Isn't that assuming
updatedAlerts
is an
Int
c
yeah. it's also not what i would recommend. for me version 1 is the kotlin way
m
@Spike Baylor I'd say give it a bit more time and you won't think anymore about '?.let' than you do 'if(!= null)'. Both will feel natural and you'll prefer the shorter one.
d
☝️
s
I hope so. I enjoy the language quite a lot. Just a few things that while nice and fun to write, i feel will be less apparent when im reading over things months later. things like if not null are very deliberate and say exactly the intent. Where myobject?.let just doesnt scream this block is happening because myobject isnt null.
d
I agree with the others that the ?. pattern is very easily recognisable once you code in Kotlin for a bit. However, I wouldn't go complaining about option 2 if I was reviewing someone else's code as it's also very clear. One could also argue that option 2 is less clear given the existing pattern of practising option 1. Normally
if
is not used to check nullability in Kotlin so your brain/eyes won't be able to skim the code as quickly as it breaks the common pattern
g
2 or
Copy code
updatedAlerts += (completedAlert ?: 0)
let is not help in this use case Even better to make
completedAlert
non-nullable
d
I’m against option 1. If you really don’t want to use
if
expression, I’d write a
ifNotNull
wrapper function around
?.let
.
👍 1
p
I like @gildor’s suggestion to make
completedAlert
non-nullable. Maybe something like that?
Copy code
val completedAlert = getAlert() ?: return
updatedAlerts += completedAlert
You can extract this in separate function.
u
apply/also would be better since you dont return
a
The let will also work on properties. (The null check won't, as the value could have been changed by the time you get to += it) I would prefer let/run over also/apply when you don't care about the return. They're shorter!
u
In my mind let read I wanna change the return, i.e. I care about ut