title: Problems with Java Generics while building a monad
body: <p>I'm playing around Java code in order to create a functional style monad, but I get struck while using generics and the Java compiler gives me a compilation error if I don't cast my object (though Generics would solve this problem!)</p>
  
  <p>This is the usage:</p>
  
  <pre><code>//COMPILATION ERROR! It requires a cast to String
  String message = If.of("Hi", s-&gt;s!=null).apply(s-&gt;s+" guys!").get();
  </code></pre>
  
  <p>Allowed: </p>
  
  <p>This is my monad:</p>
  
  <pre><code>import java.util.function.Function;
  import java.util.function.Predicate;
  
  public class If&lt;T, R&gt; {
  
    private T t;
    private Predicate predicate;
  
    private If(T t, Predicate predicate) {
      this.t = t;
      this.predicate = predicate;
    }
  
    public static&lt;T&gt; If of(T t, Predicate predicate) {
      return new If(t, predicate);
    }
  
    public If&lt;R,R&gt; apply(Function&lt;T, R&gt; function) {
      if(predicate!=null &amp;&amp; predicate.test(t)){
          return new If&lt;R, R&gt;(function.apply(t), null);
      }
      return If.of(this.t, null);
    }
  
    public T get() {
      return t;
    }
  
  }
  </code></pre>