How do you use a generic type as return value and a generic type as a parameter?

后端 未结 1 613
孤街浪徒
孤街浪徒 2021-01-25 11:05

I try to create an abstract class with generics. The business logic is to translate a text from one language to another. There must be a Translator class for each l

相关标签:
1条回答
  • 2021-01-25 11:30

    Just add it where you define your Generics :

    public abstract class Translator <T extends OriginalText, V> {            
        public abstract <V extends LanguageTranslation> V translate(T originalText);
    }
    

    Btw, this is confusing because the V definition is overriden in your method. Why not doing this :

    public abstract class Translator <T extends OriginalText, V extends LanguageTranslation> {            
        public abstract V translate(T originalText);
    }
    

    EDIT: explaining why you have a warning on V

    It's exactly the same as :

    public abstract class Translator <T extends OriginalText, V> {            
        public abstract <K extends LanguageTranslation> K translate(T originalText);
    }
    

    Now inside the method you have 3 generics :

    • K of runtime determined subtype of LanguageTranslation
    • T of runtime determined subtype of OriginalText
    • V runtime determined subtype of Object (default constraint)
    0 讨论(0)
提交回复
热议问题