Note that there are some explanatory texts on larger screens.

plurals
  1. POFitting in Java Generics for this specific use scenario
    primarykey
    data
    text
    <p>First of all sorry for the not very specific title, but i couldn't find a better and <em>short</em> descriptive one!</p> <p>I've got an Interface like so:</p> <pre><code>public interface ModelInterface { public List&lt;? extends Umbrella&gt; getBRs(); } </code></pre> <p>And and several implementing classes of this pattern:</p> <pre><code>public class Model implements ModelInterface { // need to use the concrete impl here because of JPA List&lt;StoneUmbrella&gt; _list = new ArrayList&lt;&gt;(); @Override public List&lt;? extends Umbrella&gt; getBRs() { return _list; } } </code></pre> <p>So far so good. But i also have the following Util class:</p> <pre><code>import java.util.Collection; public abstract class Util&lt;E, R&gt; { public R reduce(Collection&lt;E&gt; collection, R initialElement) { R result = initialElement; for (E currElement : collection) { result = reduce(result, currElement); } return result; } abstract R reduce(R initialElement, E element); } </code></pre> <p>Now the problem occurrs when i try to invoke that Utility class in my main code:</p> <pre><code>import java.util.List; public class Main { public static void main(String[] args) { ModelInterface model = new Model(); List&lt;? extends Umbrella&gt; list = model.getBRs(); Util&lt;Umbrella, Boolean&gt; util = new Util&lt;Umbrella, Boolean&gt;() { @Override Boolean reduce(Boolean initialElement, Umbrella element) { return Boolean.TRUE; } }; util.reduce(list, Boolean.FALSE); } } </code></pre> <p>The <em>util.reduce</em> line fails to compile with this message: The method reduce(Collection, Boolean) in the type Util is not applicable for the arguments (List&lt;capture#2-of ? extends Umbrella&gt;, Boolean)</p> <p>It works when i use List&lt;Umbrella&gt; instead of List&lt;? extends Umbrella&gt; but i can't change that in the Model Interface or i won't be able to return its internal list in the getter. I kind of think it's impossible to implement it in a way that satisfies <strong>both</strong> sides.</p> <p>Can anyone help? Thanks in advance!!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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