Consider this class:
package be.duo.test;
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.execute();
}
private void execute() {
for(int i = 0; i < 10; i++) {
System.out.println("" + method());
}
}
private int method() {
return (Math.random() > 0.5d) ? 1 : null;
}
}
The method() has return type int
, which is a primitive type.
Consider the ternary operator used in the return statement:
[ERROR] error: incompatible types: bad type in conditional expression
[ERROR] <null> cannot be converted to int
Can somebody explain to me why it behaves different?
As far as I can tell, it should be legal under Java 8.
See Table 15.25-E. Conditional expression type (Reference 3rd operand, Part III):
3rd → null
2nd ↓
int lub(Integer,null)
lub(Integer,null)
should be Integer
. Basically if you have a conditional of the form boolean ? int : null
, the result of the expression should be Integer
and it gets unboxed. (I think you already know this is what happens.)
So according to the specification it should be the same.
Seems like a compiler bug. There have been quite a few of these found, I would say try updating to the newest version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With