[ ^ CSE 341 | section index | <-- previous | next -->]

Objects and closures

Interesting aside: objects and lexical closures are "equivalent" in power. We've already seen that we can use closures to write object-oriented Scheme. Now, recall the Scheme higher-order function:

    (define (make-add-n n)
        (lambda (k) (+ k n)))

    (define add-5 (make-add-n 5))
    (add-5 4) ; => 9

Consider the following Java translation:

    public class AddN {
        private int n;
        public AddN(int n)        { this.n = n; }
        public int applyTo(int k) { return n + k; }
    }

    // ... elsewhere ...
    AddN add5 = new AddN(5);
    System.out.println( add5.applyTo(4) ); // => 9

Key insight: objects and closures are both ways of saving state (data) attached to behavior (procedures). When studying languages, it's crucial to see past syntax and recognize the deeper mechanisms. If you draw pictures of the above, they look suspiciously similar:

[Image showing similarity between Scheme closures and Java objects]

Last modified: Wed Apr 19 16:35:30 PDT 2000