“Closures are poor man's objects and vice versa” - What does this mean?

后端 未结 6 962
囚心锁ツ
囚心锁ツ 2020-11-28 02:48

Closures are poor man\'s objects and vice versa.

I have seen this statement at many places on the web (including SO) but I don\'t quite

6条回答
  •  一向
    一向 (楼主)
    2020-11-28 03:07

    "Objects are a poor man's closures" isn't just a statement of some theoretical equivalence — it's a common Java idiom. It's very common to use anonymous classes to wrap up a function that captures the current state. Here's how it's used:

    public void foo() {
        final String message = "Hey ma, I'm closed over!";
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                System.out.println(message);
            }
        });
    }
    

    This even looks a lot like the equivalent code using a closure in another language. For example, using Objective-C blocks (since Objective-C is reasonably similar to Java):

    void foo() {
        NSString *message = @"Hey ma, I'm closed over!";
        [[NSOperationQueue currentQueue] addOperationWithBlock:^{
            printf("%s\n", [message UTF8String]);
        }];
    }
    

    The only real difference is that the functionality is wrapped in the new Runnable() anonymous class instance in the Java version.

提交回复
热议问题