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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With