Generic wildcard types should not be used in return parameters

后端 未结 3 1161

Is it feasible to say that generic wildcard types should not be used in return parameters of a method?

In other words, does make sense to declare an interface like t

3条回答
  •  情歌与酒
    2020-11-27 07:27

    No, it is not feasible to say this.

    Or to put it that way: It does make sense to have such an interface.

    Imagine the following

    interface Foo  
    {
        Collection next();
    }
    
    class FooInteger implements Foo 
    {
        private final List integers = new ArrayList();
        void useInternally()
        {
            integers.add(123);
            Integer i = integers.get(0);
        }
    
        @Override
        public Collection next() 
        { 
            return integers;
        }
    }
    
    // Using it:
    Foo foo = new FooInteger();
    Collection next = foo.next();
    Number n = next.iterator().next();
    

    If you wrote the return type as Collection, you could not return a collection containing a subtype of T.

    Whether or not it is desirable to have such a return type depends on the application case. In some cases, it may simply be necessary. But if it is easy to avoid, then you can do this.


    EDIT: Edited the code to point out the difference, namely that you might not always be able to choose the type internally. However, in most cases returning something that involves a wildcard can be avoided - and as I said, if possible, it should be avoided.

    The example sketched above should still be considered as an example to emphasize the key point. Although, of course, such an implementation would be a bad practice, because it is exposing an internal state.

    In this and similar cases, one can often return something like a

    return Collections.unmodifiableList(integers);
    

    and by this, declare the return type as Colletion: The unmodifiableList method solves the problem of the exposed internal state, and has the neat property that it allows changing the type parameter to a supertype, because the list is then... well, unmodifiable anyhow.

提交回复
热议问题