Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Why should 'return' be lifted out of 'if'? (Recommended by Android studio)

The following code (simplified example):

/** Determine if a is less than 15 and b is more than 15. **/
fun isFifteenBetween(val a: Int, val b: Int) {
    if((a < 15) && (b > 15)) { return(true) }
    else { return(false) }
}

should make isFifteenBetween(3, 20) return true, and isFifteenBetween(20, 3) return false. However, I get the following recommendation from Android studio (v3.4):

Return should be lifted out of 'if'
Inspection info: This inspection reports if, when and try statements
that can be converted to expressions by lifting a return or an assignment out.
Typical example:

fun foo(arg: Boolean): String {
    when (arg) {
        true -> return "Truth"
        false -> return "Falsehood"
    }
}

The only related question I have found at stackoverflow is Kotlin: Return can be lifted out of 'when', but this doesn't quite seem to cover my case, I think.

  1. How should my code be written? I don't understand how the 'when'-expression provided by Android studio is supposed to fit in my case.
  2. Is the recommendation from Android studio simply a matter of taste and comfort, or will a change of code in this case actually make an impact on performance?
  3. Are there any guidelines available for best practise?
like image 992
SeagulFish Avatar asked Apr 22 '19 13:04

SeagulFish


1 Answers

The official convention is to prefer to return the expression itself: https://kotlinlang.org/docs/reference/coding-conventions.html#using-conditional-statements

This said the example from android studio should become:

return when (arg) {
    true -> "Truth"
    false -> "Falsehood"
} 

This will change the code of isFifteenBetween to:

/** Determine if a is less than 15 and b is more than 15. **/
fun isFifteenBetween(val a: Int, val b: Int) {
    return if((a < 15) && (b > 15)) true 
    else false
}

In terms of performance, both alternatives are almost equivalent.


These answers could be a little influenced by my opinion. but I think is more or less the reason behind. The fact of return the expression give direct impact while reading the piece of code. You know the result of the statement will be exhaustive and you have the information that every branch has been treated.

I consider this a best practice because in some case making a branching condition exhaustive could make the compiler give you an error while forgetting some new conditions. More than all for sealed classes. Further reading: https://proandroiddev.com/til-when-is-when-exhaustive-31d69f630a8b

like image 165
crgarridos Avatar answered Nov 10 '22 00:11

crgarridos