Gleb Minaev
09/20/2022, 11:50 AMJessica Ernst
09/20/2022, 12:05 PMephemient
09/20/2022, 12:05 PMGleb Minaev
09/20/2022, 12:14 PMval k: Int
if (...) k = 57
else error("Something bad occured.")
k + 179 // It compiles!
Here it could be OK to throw a compilation error because if you forgive about error
then k
is not definitely asssigned (like in some unusual use cases involving Kotlin syntax and Nothing). But it does compiles!August Lilleaas
09/20/2022, 12:16 PMerror
throws and k will always be set if it reaches the last line, so that seems safe to me 🙂Gleb Minaev
09/20/2022, 12:25 PMval kek: Int =
if (Random.nextBoolean()) 57
else {
error("Something bad happened!!!")
readln()
}
It does not compile because output type of else
block is String
when Int
is expected although this block never returns any value. So it means sometimes compiler is extra smart (as in my first example) and sometimes it is not (as in this second example). That's what shocked me.hfhbd
09/20/2022, 12:30 PMreadln(): Unreachable code
. So yeah, the data flow analysis should remove unreachable code first, then you should get a better error message.
But it will never compile because the types don't match. Although it will always throw at runtime, at compile time the types must match.ephemient
09/20/2022, 1:22 PMNothing
is recognized as unreachable,
fun foo(): Int {
TODO()
}
but this does not compile, as all returns must be of the right type.
fun foo(): Int {
TODO()
return readln()
}
now, this does compile because the unreachable code is ignored,
fun foo(): Int {
TODO()
readln()
}
but your if
-else
is not like this; the last expression is "returned" from the else branch, even if it's unreachable.Gleb Minaev
09/20/2022, 1:30 PM