https://kotlinlang.org logo
Title
w

warriorprincess

05/28/2018, 12:36 PM
any idea why the
else if
work though?
d

diesieben07

05/28/2018, 12:39 PM
Let's take this simple example (assuming it would compile):
fun myFun(input: Int): Int {
    if (input < 0) {
        return -1
    } else if (input > 0) {
        return 1
    }
}
val value = myFun(0)
what should
value
be? It's not defined in the function. That's why the function does not compile.
It declares it returns an
Int
, but for some cases there is no return value.
Alternatively (same thing):
fun myFun(input: Int): Int {
    return if (input < 0) {
         -1
    } else if (input > 0) {
        1
    }
}
👍🏼 1
c

Czar

05/28/2018, 12:41 PM
if you're using a result of an
if
tree, you have to make sure that all branches return (exhaust all conditions).
👍🏼 1
w

warriorprincess

05/28/2018, 12:44 PM
Alright that makes sense
I didn't know the compiler was smart enough to know all conditions aren't accounted for
d

diesieben07

05/28/2018, 12:45 PM
It actually isn't as smart as you think. It requires you to have an
else
block, even if your
else if
-chain already covers all cases.
w

warriorprincess

05/28/2018, 12:49 PM
Ah that makes more sense. I thought it was doing some high tech static analysis to figure out whether every path in control flow graph was accounted for