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.