title: Functors in Java
body: <p>I'm trying to define classes in Java that are similar to Haskell's functors. Hereby, a functor is defined as:</p>
  
  <pre><code>/**
   * Programming languages allow only (just simply enough) endofunctor, that are functors from and to the same category.
   * In this case, the category is the one of the datatypes (in here Type, in order to make it more clear)
   */
  public interface EndoFunctor&lt;X extends Type&gt; extends Type {
  
      /**
       * The basic implementation for any element fx
       * @param map   Transformation function for the type parameter
       * @param fx    Element of the current class
       * @param &lt;Y&gt;   Target type
       * @return      transformed element through map
       */
      &lt;Y extends Type&gt; EndoFunctor&lt;Y&gt; fmap(Function&lt;X,Y&gt; map, EndoFunctor&lt;X&gt; fx);
  
  }
  </code></pre>
  
  <p>If I want to implement a <a href="https://i.stack.imgur.com/XtbyC.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/XtbyC.gif" alt="Identity Functor over types"></a> functor, I have to write something like</p>
  
  <pre><code>public class Id&lt;X extends Type&gt; implements EndoFunctor&lt;X&gt; {
      protected X witness;
      Id(X witness) { this.witness = witness; }
      @Override
      public &lt;Y extends Type&gt; Id&lt;Y&gt; fmap(Function&lt;X, Y&gt; map, Id&lt;X&gt; fx) {
          return new Id&lt;&gt;(map.apply(fx.witness));
      }
  }
  </code></pre>
  
  <p>The problem with this code is that <code>Id&lt;X&gt;</code> does not match the type <code>EndoFunctor&lt;X&gt;</code>. How could I determine <code>fmap</code> in the <code>EndoFunctor</code> interface such that if any type <code>K&lt;T&gt;</code> implements <code>EndoFunctor&lt;T&gt;</code> and a map function <code>T-&gt;U</code> is given, then <code>K&lt;U&gt;</code> is returned as a value, without any typecasting (that is, since I know that my object is an <code>Id&lt;T&gt;</code>, then the result of <code>fmap</code> "has to be" a <code>Id&lt;U&gt;</code>, and hence I downcast the result of type <code>EndoFunctor&lt;U&gt;</code> to such type)?</p>