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

前端 未结 5 426
猫巷女王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:38

    Not that you should keep the overloaded dispatch method (I upvoted Uri for that reason), but you can force the generic version to be called by trying:

    demo.dispatch(new AlphabetSoup());
    

    or call the soup version with:

    demo.dispatch((Soup) new AlphabetSoup());
    

    The better way around this, though, is to not have the overloaded dispatch method in the first place.

    void dispatchSoup(Soup soup);
     void dispatchLetters(T letters);
    

提交回复
热议问题