What is the most clean way to rewrite this in kotl...
# getting-started
l
What is the most clean way to rewrite this in kotlin
Copy code
if ( a == null ) {
do something 
} else {
do something else
}
☝️ 1
d
That's pretty clean as it is. Unless there's more details about "do something".
l
I use a?.let { do something } but don't know how to handle when a is null
s
a?.let { do something else } ?: do something
d
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
I agree, I was just pointing out to OP how to handle the "else" case
a
@Dominaezzz But that isn't very kotlin-y right?
g
May be the "do something" should be in the A object. like
Copy code
a?.doSomething()
(edit: whops, works only if you don't have 2 branches)
d
@Abdul Kadir Depends on the use case.
👍 1
a
@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
Copy code
when (a) {
  null -> doSomething()
  else -> doSomethingElse()
}
p
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)