Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from function in Kotlin as one-liner when object is null

Tags:

kotlin

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?

like image 358
Johan Avatar asked Dec 06 '25 09:12

Johan


1 Answers

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

like image 76
elect Avatar answered Dec 11 '25 13:12

elect



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!