title: Accumulator Generator test - Java 8
body: <p>Paul Graham, in his great article <a href="http://www.paulgraham.com/icad.html" rel="nofollow">Revenge of the Nerds</a>, claimed that languages vary in power. He mentioned a nice exercise - writing an accumulator generator:</p>
  
  <blockquote>
    <p>We want to write a function that generates accumulators-- a function
    that takes a number n, and returns a function that takes another
    number i and returns n incremented by i.</p>
  </blockquote>
  
  <p>Solution in Java is</p>
  
  <pre class="lang-java prettyprint-override"><code>public class Accumulator {
  
      public interface Inttoint {
          public int call(int i);
      }
  
      public static Inttoint foo(final int n) {
          return new Inttoint() {
              int s = n;
              public int call(int i) {
                  s = s + i;
                  return s;
              }};
      }
  
      public static void main(String... args) {
          Inttoint accumulator = foo(1);
  
          System.out.println(accumulator.call(2) == 3);
          System.out.println(accumulator.call(3) == 6);
      }
  
  }
  </code></pre>
  
  <p>I am curious, whether in <strong>Java 8</strong> (thanks to lambda) is already some elegant way how to write it similarly to Groovy, see below. I tried <code>Function&lt;Integer, Integer&gt;</code></p>
  
  <p>But I stuck with this compiler error.</p>
  
  <blockquote>
    <p>local variables referenced from a lambda expression must be final or
    effectively final</p>
  </blockquote>
  
  <p>So do you have some Java 8 solution?</p>
  
  <p>Compare the old Java solution with the Groovy one</p>
  
  <pre><code>def foo(n) {
      return {n += it}
  }
  
  def accumulator = foo(1)
  assert accumulator(2) == 3
  assert accumulator(3) == 6
  </code></pre>