any idea why the `else if` work though?
# announcements
w
any idea why the
else if
work though?
d
Let's take this simple example (assuming it would compile):
Copy code
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):
Copy code
fun myFun(input: Int): Int {
    return if (input < 0) {
         -1
    } else if (input > 0) {
        1
    }
}
👍🏼 1
c
if you're using a result of an
if
tree, you have to make sure that all branches return (exhaust all conditions).
👍🏼 1
w
Alright that makes sense
I didn't know the compiler was smart enough to know all conditions aren't accounted for
d
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
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