title: Java 8 - Inferring generic return type with lambdas
body: <p>I am trying to preserve the Generic type information from the return type of a lambda expression across some higher-order-functions in Java 8. I have simplified my actual code down to this test case. The problem is not what I expect the code to do exactly, but rather than I expect the generic type(s) <code>R</code> to be inferred as <code>java.lang.String</code> and carried through the function calls.</p>
  
  <pre><code>import java.util.function.Function;
  
  public class AdamTest {
  
      public final static void main(final String args[]) {
          final AdamTest adamTest = new AdamTest();
  
          final String s = adamTest.thing2(7).apply(i -&gt; i.toString());
          System.out.println(s);
      }
  
  
      private &lt;R&gt; R fn1(final Function&lt;Integer, R&gt; op) {
          return op.apply(10);
      }
  
      private &lt;R&gt; Function&lt;Function&lt;Integer, R&gt;, R&gt; thing2(final Integer val) {
          return fn1(i -&gt; new Function&lt;Function&lt;Integer, R&gt;, R&gt;() {
                  @Override
                  public R apply(Function&lt;Integer, R&gt; op) {
                      return op.apply(val * i);
                  }
              }
          );
      }
  }
  </code></pre>
  
  <p>At the moment this code does not compile because of this line <code>final String s = adamTest.thing2(7).apply(i -&gt; i.toString());</code>. I think I have something subtly wrong with my type bounds, as the compiler does not seem to be able to infer the return type of <code>thing2(7).apply</code> and reports <code>Object</code> rather than <code>String</code> which I was hoping for.</p>
  
  <p>How do I get the generic type bounds correct so that the correct return type i.e. <code>java.lang.String</code> is <strong><em>inferred</em></strong> by the compiler?</p>