Why does this not trigger a warning, when it works...
# getting-started
a
Why does this not trigger a warning, when it works for Ints?
Copy code
val zero = if (condition) 0f else 0f
val division = 1f / zero // no division by zero warning
Of course proper test coverage would catch this easily, but given that tests are written by humans, sometimes it slips through.
e
division by floating point zero is not an error
a
Oh yes, infinity. But then there's this inconsistency:
e
ah, I guess that's an IDE limitation. it doesn't seem to warn about
Copy code
val zero = if (condition) 0 else 0
val division = 1 / zero
either
r
Surprised there isn't a specific warning for
if (x) y else y
I suppose it'd be difficult to detect in anything other than the most simple cases but that's also true of division by zero ūü§∑
Actually, ignore that, kotlin compiler doesn't try to make any guarantees about runtime correctness (that's why we have tools like detekt)
You only get the divide by zero warning when it tries to do the division at compile time
Which in this case looks like an implementation detail of the compiler:
We use the term ‚Äúconstant expression‚ÄĚ to refer to any expression constructed of the following:
constant literals
access expressions to enum entries
string interpolation over constant expressions
an implementation-defined set of functions that can always be evaluated at compile-time
Fun fact: Java does actually guarantee that this will happen at compile time if the condition is a constant
So the Java equivalent will give the expected warning on both lines:
``` int x = true ? 0 : 0;
int y = 1 / x;```