Note that there are some explanatory texts on larger screens.

plurals
  1. POInferred wildcard generics in return type
    primarykey
    data
    text
    <p>Java can often infer generics based on the arguments (and even on the return type, in contrast to e.g. C#).</p> <p>Case in point: I've got a generic class <code>Pair&lt;T1, T2&gt;</code> which just stores a pair of values and can be used in the following way:</p> <pre><code>Pair&lt;String, String&gt; pair = Pair.of("Hello", "World"); </code></pre> <p>The method <code>of</code> looks just like this:</p> <pre><code>public static &lt;T1, T2&gt; Pair&lt;T1, T2&gt; of(T1 first, T2 second) { return new Pair&lt;T1, T2&gt;(first, second); } </code></pre> <p>Very nice. However, this no longer works for the following use-case, which requires wildcards:</p> <pre><code>Pair&lt;Class&lt;?&gt;, String&gt; pair = Pair.of((Class&lt;?&gt;) List.class, "hello"); </code></pre> <p>(Notice the explicit cast to make <code>List.class</code> the correct type.)</p> <p>The code fails with the following error (provided by Eclipse):</p> <blockquote> <p>Type mismatch: cannot convert from <code>TestClass.Pair&lt;Class&lt;capture#1-of ?&gt;,String&gt;</code> to <code>TestClass.Pair&lt;Class&lt;?&gt;,String&gt;</code></p> </blockquote> <p>However, explicitly calling the constructor still works as expected:</p> <pre><code>Pair&lt;Class&lt;?&gt;, String&gt; pair = new Pair&lt;Class&lt;?&gt;, String&gt;((Class&lt;?&gt;) List.class, "hello"); </code></pre> <p>Can someone explain this behaviour? Is it by design? Is it <em>wanted</em>? Am I doing something wrong or did I stumble upon a flaw in the design / bug in the compiler?</p> <p>Wild guess: the “capture#1-of ?” somehow seems to imply that the wildcard is filled in by the compiler on the fly, making the type a <code>Class&lt;List&gt;</code>, and thus failing the conversion (from <code>Pair&lt;Class&lt;?&gt;, String&gt;</code> to <code>Pair&lt;Class&lt;List&gt;, String&gt;</code>). Is this right? Is there a way to work around this?</p> <hr> <p>For completeness’ sake, here is a simplified version of the <code>Pair</code> class:</p> <pre><code>public final class Pair&lt;T1, T2&gt; { public final T1 first; public final T2 second; public Pair(T1 first, T2 second) { this.first = first; this.second = second; } public static &lt;T1, T2&gt; Pair&lt;T1, T2&gt; of(T1 first, T2 second) { return new Pair&lt;T1, T2&gt;(first, second); } } </code></pre>
    singulars
    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.
 

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