https://kotlinlang.org logo
Title
g

Gyuhyeon

10/21/2019, 8:44 AM
New to kotlin, and I've been trying to figure out what the best practices are for null checks in kotlin. The suggestions are all over the place, and they rarely consider usages other than a single liner. I'd like some opinions on the following:
if (someObj != null) {
    val someOtherLogic = repository.selectOne(someObj.field)
    someOtherLogic.doThis()
    someOtherLogic.doThat()
} else {
    someService.someBusinessLogic()
}
apparently, checking null with
if
statements is not the "kotlin way". [citation needed] from what I've gathered, the "kotlin way" is the following.
someObj?.also {
    val someOtherLogic = repository.selectOne(someObj.field)
    someOtherLogic.doThis()
    someOtherLogic.doThat()
} ?: run {
    someService.someBusinessLogic()
}
but honestly, this looks like some serious code-smell to me. Maybe it's because I come from java, but if what the code is trying to achieve is
do some business logic based on the isExists state of an object and do something else if it doesn't exist
, using
?.also{} ?: run{}
seems way worse than an explicit easy to read
if / else
. Any input would be appreciated.
w

wasyl

10/21/2019, 8:48 AM
`if`s are fine, especially in the scenario like yours. It’s only tricky if
someObj
is a nullable property, in which it will not be smart-cast inside the
if
block.
Sometimes
?.let
,
?.also
etc. will be more readable, but if Kotlin didn’t want us to use `if`s they’d have not included it in the language 😉
g

Gyuhyeon

10/21/2019, 8:52 AM
thanks for the input - I'm guessing you mistyped
mutable property
as
nullable property
?
w

wasyl

10/21/2019, 8:59 AM
yes, well it would have to be both nullable and mutable for this to be a problem I think
r

ribesg

10/21/2019, 9:14 AM
Even if it was mutabe & nullable I would prefer to do
val someObj = someObj
before doing an
if
rather than the monstruosity that is your second code bloc
👆 1
d

Dico

10/21/2019, 9:26 AM
I prefer the first as well.
t

toffe

10/21/2019, 10:47 AM
Readability > all (other words: use the if one)
s

Stephan Schroeder

10/21/2019, 3:28 PM
I like this book as a source of Best Practices https://leanpub.com/effectivekotlin