Java generics : Type mismatch: cannot convert from Integer to K

后端 未结 1 1288
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 23:37

Following code is throwing compile time exception

Type mismatch: cannot convert from Integer to K

What I understand is K

相关标签:
1条回答
  • 2020-12-04 00:01

    The problem here is the fact that K is a type that extends Number but it is an unknown sub class of Number that is why the compiler raises this error because Integer is only one specific sub class of Number so it cannot match with any potential target types.

    Let's say that you want to cast it explicitly to make it compile with

    public <K extends Number> K getValue(){
        Integer a = new Integer(1);
        return (K) a;
    }
    

    Then if you call it expecting any sub class of Number except Integer you will get a ClassCastException, that is exactly what the compiler wants to avoid:

    Double d = getValue(); <-- throws ClassCastException
    

    As workaround you could define your method using Number as returned type as next:

    public Number getValue() {
        return new Integer(1);
    }
    
    0 讨论(0)
提交回复
热议问题