How do I resolve ambiguous methods caused by intersection types in Java generics?

前端 未结 5 401
猫巷女王i
猫巷女王i 2020-12-31 16:52

I just recently discovered that you can specify multiple types in a single type parameter bound (see example). Like any new tool, I\'ve been trying to explore the possibilit

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 17:37

    Note that the error is not related to generics, you get the same result if you use interfaces and a type is the intersection:

    public class AA {
    
        interface XX{};
        interface YY{};
    
        public void doSomething(XX x){}
        public void doSomething(YY x){}
    
        class XY implements XX,YY{
    
        }
    
        public void runner(){
            doSomething(new XY());
        }
    }
    

    You get the same error in "doSomething", the compiler cannot resolve the ambiguity. Do you want to interpret as XX or as YY? You have to specify it with a cast. But if you have a hierarchy, like "YY extends XX" and "XY implements YY", the compiler can infer the correct method to call.

提交回复
热议问题