https://kotlinlang.org logo
Title
l

lsk

01/02/2019, 10:03 PM
What is the most clean way to rewrite this in kotlin
if ( a == null ) {
do something 
} else {
do something else
}
☝️ 1
d

Dominaezzz

01/02/2019, 10:15 PM
That's pretty clean as it is. Unless there's more details about "do something".
l

lsk

01/02/2019, 10:26 PM
I use a?.let { do something } but don't know how to handle when a is null
s

stephan_marshay

01/02/2019, 10:28 PM
a?.let { do something else } ?: do something
d

Dominaezzz

01/02/2019, 10:30 PM
In my opinion, for your use case I suggest keeping it simple with if/else. Or you'll end up with awkward chains of
?:
and
?.
.
3
👆 3
s

stephan_marshay

01/02/2019, 10:35 PM
I agree, I was just pointing out to OP how to handle the "else" case
a

Abdul Kadir

01/03/2019, 6:12 AM
@Dominaezzz But that isn't very kotlin-y right?
g

gaspard

01/03/2019, 8:24 AM
May be the "do something" should be in the A object. like
a?.doSomething()
(edit: whops, works only if you don't have 2 branches)
d

Dominaezzz

01/03/2019, 8:35 AM
@Abdul Kadir Depends on the use case.
👍 1
a

Alowaniak

01/03/2019, 12:24 PM
@stephan_marshay that doesn't necessarily handle the "else" case though? If whatever is in the let expression returns
null
then it will also execute whatever after
?:
was You would have to use
also
or
apply
then Personally I might go for a
when (a) {
  null -> doSomething()
  else -> doSomethingElse()
}
p

psilospore

01/07/2019, 2:12 PM
https://arrow-kt.io/docs/arrow/core/option/ (disclaimer I haven't used kotlin much but IMO options are the cleanest way of handling nullality)