[Prev][Next][Index][Thread]

Re: Closures



Jeff Dalton wrote:
> Start with the first definition of Test below.  It's one that actually
> works in Java, because the "closures" refer to a RefInt object that
> contains an int, and so there's no assignment to i, only to i.val.

Another way to get around the restriction (that still works in Java) is
to wrap both "closures" in a third "closure" and use a field to hold i
instead of a local variable.  This technique is essentially equivalent
to the use of the let form in Scheme, which uses a closure to create new
bindings.

(Like your example, this one doesn't actually demonstrate that the
closures can be returned out of the scope of i, but they can.)

class Test {
  public static void main(String[] argv) {
    new Runnable() {
        int i = 0;
        public void run() {
          Runnable closure1 = new Runnable() {
              public void run() {
                i = i + 1;
              }
            };
          Runnable closure2 = new Runnable() {
              public void run() {
                i = i + 3;
              }
            };
          System.out.println("Initial value = " + i);
          for (int count = 1; count <= 10; count++) {
            System.out.print("Iteration " + count + ": ");
            closure1.run();
            System.out.print("after closure1, " + i  + "; ");
            closure2.run();
            System.out.println("after closure2, " + i + ". ");
          }
        }
      }.run();
  }
}