how can i do ```dataList?.size+1 ?: 0``` basical...
# announcements
f
how can i do
Copy code
dataList?.size+1 ?: 0
basically, if datalist isnt null, return its size+1. else, 0
k
val size: Int = list?.let { it.size + 1 } ?: 0
🙂 1
s
Does that really have much benefit over an
if/else
?
k
eye of the beholder 🤷
s
Is there any kind of performance penalty with the extra lambda there?
k
i don’t know what the bytecode becomes. if worried, if/else would work too
val size: Int = if (list == null) 0 else list.size + 1
s
dataList?.size?.let { it + 1 } ?: 0
d
Shouldn’t be much of one,
let
is inline.
s
Copy code
val size = list?.size?.plus(1) ?: 0
🤔
d
(dataList?.size ?: -1) + 1
🧌
🧌 7
s
you monster
😛
k
well this got out of hand
s
better in a thread than spamming #general I guess
f
@dalexander lol. ya thought of that (for a workaround) but it is not clean
@Shawn that would check if size is null
s
would it not essentially do what the
size?.let
block does?
d
I think Shawn’s last suggestion is probably the best, I think using
let
is probably worse than just using
if/else
s
if you wanna be even more clever about it, perhaps
Copy code
dataList?.size?.inc() ?: 0
but I’m not sure how that works with r/o properties
f
dataList?.size?.inc() ?: 0
will also check if size == null, then return 0. else inc(). but size can never be null. so elvis operator is useless here
d
Size can definitely be null,
?.
doesn’t short-circuit the statement if there’s a null value (unlike C#)
s
whoa, TIL
f
you're right
s
https://kotlinlang.org/docs/reference/null-safety.html#safe-calls the copy seems to kinda imply it does just short-circuit if it is null, but maybe that’s just me reading it a bit over eagerly
f
could you give me a case where size can be null
d
if
dataList
is null then
dataList?.size
will evaluate to null.
👍 1
s
if
dataList
is
null
,
null?.size
would also be null
👍 1
d
Oh, I guess I should clarify, after poking at
?.
for a few minutes, it doesn’t call methods if the receiver is null, but it will continue to traverse the statement, which is a bit more nuanced behavior.
s
@dalexander ahh, gotcha. good to know 👍
d
this is my test statement
dataList?.size?.let { println("First") }.let { println("Second") }
it prints “First\n Second” if dataList is null, otherwise just “Second” (because the second let statement doesn’t use
?.
a
but be aware of the fact that if the lambda of
let
returns
null
, the elvis part will still be called
try:
""Hello World"?.let { println("Not null"); return@let null } ?: println("Its null :(")