title: Seeking clarification regarding type erasure and type inference
body: <pre><code>class Undoable&lt;T&gt; {
    T value;
    Deque&lt;Object&gt; history;
        
    Undoable(T t, Deque&lt;Object&gt; history) {
      this.value = t;
      this.history = history;
    }
    
    static &lt;T&gt; Undoable&lt;T&gt; of(T t) {
      return new Undoable&lt;T&gt;(t, new LinkedList&lt;Object&gt;());
    }
  
    public &lt;R&gt; Undoable&lt;R&gt; flatMap(Function&lt;T, Undoable&lt;R&gt;&gt; mapper) {
      Undoable&lt;R&gt; r = mapper.apply(value);
      Deque&lt;Object&gt; newHistory = new LinkedList&lt;&gt;();
      newHistory.addAll(history);
      newHistory.addAll(r.history);
      return new Undoable&lt;R&gt;(r.value, newHistory);
    }
  
    public &lt;R&gt; Undoable&lt;R&gt; undo() {
      Deque&lt;Object&gt; newHistory = new LinkedList&lt;&gt;(this.history);
      R r;
      try {
        r = (R)newHistory.removeLast(); //line A
      } catch (NoSuchElementException e) {
        throw new CannotUndoException();
      }
      return new Undoable&lt;R&gt;(r, newHistory);
    }
  }
  </code></pre>
  <p>Given the code snippet above, let say we leave Line A as it is and ignore the compilation warning. What would happen if we</p>
  <pre><code>Undoable&lt;Integer&gt; i = Undoable.of(&quot;hello&quot;).flatMap(s -&gt; {
      Deque&lt;Object&gt; history;
      history = new LinkedList&lt;&gt;();
      history.add(s);
      return new Undoable&lt;Integer&gt;(s.length(), history);
  });
  Undoable&lt;Double&gt; d = i.undo();
  </code></pre>
  <p>I get that <code>Undoable&lt;Integer&gt;</code> and <code>Undoable&lt;Double&gt;</code> erases to <code>Undoable</code>. But what does <code>R</code> in the <code>undo()</code> method become? Does it infer to be <code>Double</code> since <code>Double</code> is the target type of that method call?</p>
  <p>I've tried running the code on my machine and it runs fine but I have no idea why. Can anyone shed some light? Thanks a ton!</p>