Early return in Kotlin

In programming, there is an open discussion as to whether you should only have one return statement.
You can use these two options (or more with variations or more arguments):

// Single return
fun function1(argA: Any?) {
    if(argA != null){
        //do the magic
       return
    }
}

//Multiple return
fun function2(argA: Any?) {
    if(argA == null) return
    //do the magic
    return
}

I prefer the second option, to have more than one return statement. I see it as more readable, but I only use it for validation and these returns should be on the top of the function. Can we make it better in Kotlin?

Yes! Take a look at this simplest and shortest solution for null validation:

 argA ?: return

But it would be good to log what happened and in this case you can’t add anything else to the Elvis operator. But fortunately, there is a run function!

argA ?: run {
    Timber.w("argA is null")
    return
}

This is my preferred way to return early with a log. Unfortunately, this works only for a null validation. In other cases, you can try with takeIf or takeUnless function. However, I am not convinced about this and still think that if statement is more readable in this case.

// Prefere this
if( argA < MAGIC_LIMIT_VALUE)  { 
    Timber.w("argA=$argA is greater than MAGIC_LIMIT_VALUE")
    return
}

// Over this
argA.takeUnless { it < MAGIC_LIMIT_VALUE } ?: run {
    Timber.w("argA=$argA is greater than MAGIC_LIMIT_VALUE")
    return
}

Approach with the Elvis operator is better when it comes to guard assignments.

// Prefere this
val value = argA.takeIf { it < MAGIC_LIMIT_VALUE } ?: return

// Over this
val value = if( argA < MAGIC_LIMIT_VALUE)  argA else ?: return

Tell me what is your opinion and your best practices about it?
Do you use the Elvis operator often?
Do you log when you return early?

Have a great day!
See you on The Code Side
Artur Latoszewski

Add a Comment

Your email address will not be published.