title: Java generics: How to encode a Functor interface in Java?
body: <p>I want to define a Functor class in Java. This works:</p>
  
  <pre><code>//a Function
  public interface F&lt;A,R&gt; {
     public R apply(A a);
  }
  
  public interface Functor&lt;A&gt; {
     public &lt;B&gt; Functor&lt;B&gt; fmap(F&lt;A,B&gt; f);
  }
  </code></pre>
  
  <p>However the return value of fmap should be not <code>Functor</code>, but the appropriate subclass. Usually this can be encoded with the <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">CRTP</a>, but here I seem to hit a wall because of the additional parameter <code>A</code>. E.g. the following and similar encodings don't work ("type parameter FInst is not within its bounds"):</p>
  
  <pre><code>public interface Functor&lt;A, FInst extends Functor&lt;A,FInst&gt;&gt; {
      public &lt;B, I extends Functor&lt;B,FInst&gt;&gt; I fmap(F&lt;A,B&gt; f);
  }
  </code></pre>
  
  <p><strong>[Clarification]</strong></p>
  
  <p>With "appropriate subclass" I mean the type of the class being called itself. E.g. Lists are functors, so I would like to write something like </p>
  
  <pre><code>public class ListFunctor&lt;A&gt; implements ??? {
    final private List&lt;A&gt; list;
    public ListFunctor(List&lt;A&gt; list) {
       this.list = list;
    } 
  
    @Override
    &lt;B&gt; ListFunctor&lt;B&gt; fmap(F&lt;A,B&gt; f) {
       List&lt;B&gt; result = new ArrayList&lt;B&gt;();
       for(A a: list) result.add(f.apply(a));
       return new ListFunctor&lt;B&gt;(result); 
    }  
  }
  </code></pre>
  
  <p>I'm aware that I could write this even with the first definition I gave (because covariant return types are allowed), but I want that the return type "ListFunctor" is <strong>enforced</strong> by the type system (so that I can't return a FooFunctor instead), which means that the Functor interface needs to return the "self-type" (at least it is called so in other languages). </p>
  
  <p><strong>[Result]</strong></p>
  
  <p>So it seems what I want is impossible. Here is a related blog-post: <a href="http://blog.tmorris.net/higher-order-polymorphism-for-pseudo-java/" rel="nofollow noreferrer">http://blog.tmorris.net/higher-order-polymorphism-for-pseudo-java/</a></p>
  
  <p><strong>[Aftermath]</strong></p>
  
  <p>I stumbled over this age-old question of mine, and realized that this was the starting point of the amazing journey with my library <a href="https://github.com/highj/highj" rel="nofollow noreferrer">highJ</a>, containing much more than a simple <code>Functor</code>. I would have never imagine that people would use this crazy stuff for anything serious, but it happened, and that makes me very happy. </p>