I found a piece of code that after switching from Java 7 to Java 8 stopped compiling. It does not feature any of the new Java 8 stuff like lambda or streams.
I narrowed
CompileMe.java:4: error: incompatible types: bad type in
conditional expression
Double d = g == null ? 0 : g.getData(); // type error!!!
int cannot be converted to Double
Here 0 is integer and you are putting it inside Double.
Try this
public class CompileMe {
public static void main(String[] args) {
GenericData g = new GenericData(1d);
Double d = g == null ? 0d : g.getData(); // type error!!!
Double d2 = g == null ? 0d : g.data; // now why does this work...
System.out.println(d);
System.out.println(d2);
}
}
class GenericData {
public T data;
public GenericData(T data) {
this.data = data;
}
public T getData() {
return data;
}
}
Or use double literal instead of Double wrapper class
public class CompileMe {
public static void main(String[] args) {
GenericData g = new GenericData(1d);
double d = g == null ? 0 : g.getData(); // type error!!!
double d2 = g == null ? 0 : g.data; // now why does this work...
System.out.println(d);
System.out.println(d2);
}
}
class GenericData {
public T data;
public GenericData(T data) {
this.data = data;
}
public T getData() {
return data;
}
}
Because widening and boxing will not take place simultaneously.