My question is about Odersky’s lecture 3.5 (not the assignment!):
The exercise at 19:15 asks: “What is the type of: if (true) 1 else false“
In his explanation, Odersky argues that the type is AnyVal because it is the most specific supertype of Int and Boolean (the types of the two conditional branches).
I am asking myself why the type checker is not smart enough to see that only the first branch is actually relevant, and the type could thus be inferred to Int?
It’s a similar question to why the following does not compile in Java:
but this compiles:
Basically the compiler has to stop somewhere. Especially the Scala compiler, which is already quite slow. Once it recognizes
trueas always passing condition, one might ask: what about:1 == 1,2 * 21 == 42or evenx == 7wherexisval.It’s hard to draw a line so the compiler simply assumes every
ifcan have both branches. It’s the responsibility of IDE or code validation tools to discover such impossible or probably incorrect expressions.