Reputation: 40500
I have a Java method that looks like this:
void doStuff() {
MyObject myObject = myObjectRepository.findById(myObjectId);
if (myObject == null) {
log.warn("myObject not found, aborting");
return;
}
// More stuff
}
Is there a way to make this a one-liner in Kotlin? I'm thinking something like this (which doesn't work):
fun doStuff() {
// I'd like to do something here that returns from the doStuff function when myObject is null
val myObject = myObjectRepository.findById(myObjectId)
?: {log.warn("myObject not found, aborting") return}
// More stuff
}
Can you do something like this Kotlin?
Upvotes: 2
Views: 1219
Reputation: 4608
val myObject = myObjectRepository.findById(myObjectId)?:run {
log.warn("myObject not found, aborting"); return
}
//more stuff
Upvotes: 4
Reputation: 7190
fun doStuff() {
val myObject = myObjectRepository.findById(myObjectId)
?: log.warn("myObject not found, aborting").also{ return }
// More stuff
}
But I'd agree with DPM, a classical if-else
is a better option.
You may want to consider also the when
construct (depending on the size, the task of the function and the return type):
fun doStuff() {
val myObject = myObjectRepository.findById(myObjectId)
return when {
myObject == null -> log.warn("myObject not found, aborting") // Unit?
else -> // More stuff
}
}
One of the reason you may prefer a when
over an if-else
is also because I find it exploits better the space (a readable if-else
use at least 4, sometimes 5, loc) and it's more legible because you have the keyword when
at the same level of the return (or assign, or whatever) and each case pure and simple without any additional keywords, simply a non-literal sign ->
that clearly states the condition from the code.
However, also
is an extention function offered by the kotlin standard lib.
It's one of the features I love most about Kotlin which gives you a lot of power and expressiveness.
Let me suggest you this link to further investigate and learn more about other useful functions, such run
, let
, apply
, takeUnless
and takeIf
Upvotes: 5