Reputation: 1
I have a function that accepts nullable Strings, but requires them to be non-null.
fun fn(a: String?) {
if (a == null) {
logger.warn("a is null, aborting")
return
}
// do something
fnThatDoesNotAcceptNulls(a)
}
Is there a better way to check if the value is null and return
from the function in Kotlin?
Upvotes: 0
Views: 72
Reputation: 5447
You can resolve this problem by:
if
(your version)fun fn(a: String?) {
if (a == null) {
logger.warn("a is null, aborting")
return
}
// do something
fnThatDoesNotAcceptNulls(a)
}
if
fun fn(a: String?) {
if (a != null) {
// do something
fnThatDoesNotAcceptNulls(a)
return
}
logger.warn("a is null, aborting")
}
if
(but without logging):fun fn(a: String?) {
if (a != null) {
// do something
fnThatDoesNotAcceptNulls(a)
}
}
if-else
fun fn(a: String?) {
if (a == null) {
logger.warn("a is null, aborting")
} else {
// do something
fnThatDoesNotAcceptNulls(a)
}
}
when
(with expression body - depends on return type!):fun fn(a: String?) = when (a) {
null -> {
logger.warn("a is null, aborting")
}
else -> {
// do something
fnThatDoesNotAcceptNulls(a)
}
}
?:
)fun fn(a: String?) {
val value = a ?: return
// do something
fnThatDoesNotAcceptNulls(value)
}
let
extension:fun fn(a: String?) {
a?.let {
// do something
fnThatDoesNotAcceptNulls(it)
}
}
let
extension (with handling "negative" case when a
is null):fun fn(a: String?) {
a?.let {
fnThatDoesNotAcceptNulls(a)
} ?: logger.warn("a is null, aborting")
}
run
extension:fun fn(a: String?) {
a?.run {
// do something
fnThatDoesNotAcceptNulls(this)
}
}
run
extension (with handling "negative" case when a
is null):fun fn(a: String?) {
a?.run {
// do something
fnThatDoesNotAcceptNulls(this)
} ?: logger.warn("a is null, aborting")
}
In private, I like option 5 (with elvis) and those with extensions. But it all depends on the situation or the case.
Upvotes: 3