Java 8 autoboxing + generics: different behaviour with variable vs. method

前端 未结 4 752
日久生厌
日久生厌 2021-02-07 07:43

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

4条回答
  •  悲哀的现实
    2021-02-07 08:15

    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.

提交回复
热议问题