Is there any kotlinian way to avoid an if else aft...
# announcements
p
Is there any kotlinian way to avoid an if else after a
find
or
firstOfNull
?
Copy code
val foo = bar.firstOfNull {whatever}
if(foo==null) smthing()
else smthing2()
e
bar.find { whatever}?.let { smthng(it) } ?: smthng2()
👆 1
v
That has a bug though,
let
returns the result of the lambda. So if
smthng
returns
null
, both methods would be executed. Better would be
Copy code
bar.firstOrNull { whatever }?.also { smthng() } ?: smthng2()
Except if
smthing()
can never return
null
, then it shouldn't make a difference
j
if else is better, it is readable
☝🏼 1
☝️ 4
v
That's a matter of taste, but I agree 😄
🙂 1
j
I think an if/else without object allocation is perhaps better
Copy code
if (bar.any { whatever }) {
    smthing()
}
else {
    smthing2()
}
👍 2
d
"kotlinian" That's a new one for me.
j
All these Kotlin words, it's Krazy K
n
If you actually need the object but want to avoid giving it a name that leaks to the surrounding scope there's also
Copy code
bar.firstOrNull { whatever }.run {
    if (it == null) {
        something()
    else {
        something2(it)
    }
}