title: Java 8 Functions - compose and andThen
body: <p>I find my Java knowledge out-of-date with Java 8, and there are many new language features I am trying to learn. One of them is Functions, specifically the <code>compose</code> and <code>andThen</code> methods.</p>
  
  <p>I have written a trivial experiment to test the reversibility of <code>compose</code> and <code>andThen</code>:</p>
  
  <pre><code>/** Wraps a value 
   */
  public class Wrap&lt;T&gt; {
      private final T value;
      private Wrap(T value) {
          this.value = value;
      }
      public static &lt;T&gt; Wrap&lt;T&gt; of(T value) {
          return new Wrap&lt;&gt;(value);
      }
  }
  
  static void functions() {
  
      Function&lt;Integer,String&gt; itos = i-&gt;"'"+i+"'";
      Function&lt;String,Wrap&lt;String&gt;&gt; stow = s-&gt;Wrap.of(s);
  
      Function&lt;Integer,Wrap&lt;String&gt;&gt; itow = itos.andThen(stow);
      Function&lt;Integer,Wrap&lt;String&gt;&gt; itow2 = stow.compose(itos);
  
      System.out.println(itow.apply(3));
      System.out.println(itow2.apply(3));
  }
  </code></pre>
  
  <p>In the above code, as expected, the 2 Functions <code>itow</code> and <code>itow2</code> seem to be equivalent. But are they actually equivalent? Do the have the same result somewhat by accident in this case?</p>
  
  <p>The thought occurs that both <code>compose</code> and <code>andThen</code> methods exist for a reason, and that Functions or BiFunctions might not always be reversible in this way. Can you think of any cases where the reversibility would not apply?</p>