Note that there are some explanatory texts on larger screens.

plurals
  1. POAdapter from Interface<Type> to Interface<Subtype>
    text
    copied!<p>Consider the following interface.</p> <pre><code>public interface Feed&lt;T&gt; { public void put( T o ); } </code></pre> <p>We have a straightforward Java class implementing this interface, that writes objects to a specific collection.</p> <pre><code>public class CollectionFiller&lt;T&gt; implements Feed&lt;T&gt; { private final Collection&lt;T&gt; collection; private CollectionFiller( Collection&lt;T&gt; collection ) { this.collection = collection; } public void put( T o ) { this.collection.add( o ); } public static &lt;T&gt; CollectionFiller&lt;T&gt; of( Collection&lt;T&gt; collection ) { return new CollectionFiller&lt;T&gt;( collection ); } } </code></pre> <p>Now we define two dummy classes, in order to make the question concrete.</p> <pre><code>public class Super {} public class Sub extends Super {} </code></pre> <p>Let's say there is some method <code>writeSubsTo( Feed&lt;Sub&gt; f )</code> and we have an instance <code>cf</code> of <code>CollectionFiller&lt;Super&gt;</code>. Since <code>cf</code> only adds objects to its collection of "Supers", it would be safe to pass it to <code>writeSubsTo</code>. The compiler won't allow it however. (The reason for this behavior is clear to me.)</p> <p>I wanted to write a convenience adapter that wraps around a <code>CollectionFiller</code> of type X and poses as a <code>Feed</code> of a specific subtype of type X. I tried (among many other things) the following, but the compiler gives me trouble.</p> <pre><code>class SubFiller&lt;T1, T2 extends T1&gt; implements Feed&lt;T2&gt; { private final CollectionFiller&lt;T1&gt; collectionFiller; SubFiller( CollectionFiller&lt;T1&gt; collectionFiller ) { this.collectionFiller = collectionFiller; } public void put( T2 o ) { this.collectionFiller.put( o ); } public static &lt;T1, T2 extends T1&gt; SubFiller&lt;T1, T2&gt; of( CollectionFiller&lt;T1&gt; c ) { return new SubFiller&lt;T1, T2&gt;( c ); } } </code></pre> <p>Although there is nothing wrong with this class, the compiler won't accept both of the last two statments in the following code fragment.</p> <pre><code>CollectionFiller&lt;Super&gt; cf = CollectionFiller.of( new HashSet&lt;Super&gt;() ); SubFiller&lt;Super, Sub&gt; sf = SubFiller.of( cf ); writeSubsTo( SubFiller.of( cf ) ); </code></pre> <p>Can anyone think of a nice way of solving this problem? I wouldn't mind if the adapter contained cumbersome code, as long as using it is not too verbose (hence the static factory methods). Of course, any other solution (not using an adapter) is also fine (again, as long as using it isn't too verbose).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload