New to kotlin, and I've been trying to figure out ...
# announcements
g
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:
Copy code
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.
Copy code
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
`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
thanks for the input - I'm guessing you mistyped
mutable property
as
nullable property
?
w
yes, well it would have to be both nullable and mutable for this to be a problem I think
r
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
I prefer the first as well.
t
Readability > all (other words: use the if one)
s
I like this book as a source of Best Practices https://leanpub.com/effectivekotlin