When is there need for Some> instead of Some?

后端 未结 4 1275
执笔经年
执笔经年 2020-12-20 15:59

NOTE: This question is not Enum-related, so it\'s not duplicate. Enum\'s are forced to compare only-with-itself because compiler generation of type paramete

4条回答
  •  温柔的废话
    2020-12-20 16:34

    The difference is that Some means two things:

    • E is a raw type. In brief, raw types have all generic information stripped from the class, which in turn can create unexpected behaviour
    • E can be any class of Some!

    Conversely, using Some> means:

    • E is typed
    • E must be the same class as the class in which it's declared

    The raw part an issue, but the bigger implication is the type bounds. This code demonstrates the difference, with the "B" classes using (or trying to use) the "A" classes as the generic type.

    // The raw version
    interface Some {
        E get();
    }
    
    class SomeA implements Some {
        public  SomeA get() {
             return new SomeA();
        }
    }
    
    // Compiles OK
    class SomeB implements Some {
       public SomeA get() {
             return new SomeA();
        }
    }
    
    // The typed version
    interface SomeT> {
        E get();
    }
    
    class SomeTA implements Some {
        public  SomeTA get() {
             return new SomeTA();
        }
    }
    
    // Compile error 
    class SomeTB implements SomeT {
       public SomeA get() { 
             return new SomeTA();
       }
    }
    

    Class SomeB compiles fine - the type of E is bound only to Some, so any Some class will do, but class SomeTB throws a compile error:

    type argument SomeTA is not within bounds of type-variable E

    The type of E must be exactly the same as the containing class.

    This is important if you're expecting parameters and return types to be the same as the class itself, which is usually what you want with typed classes.


    The type being bounded by a raw type is less of an issue, because it's still a Some, but there may be cases where it makes a difference (I can't think of any just now).

提交回复
热议问题