Alex Rivera | Logout

Closures: why are they so useful?

Asked 2009-08-20T11:36:44.863
69

As an OO developer, maybe I have difficulty seeing its value. What added value do they give? Do they fit in an OO world?

Edit
Report

2 Answers

5

IMHO it comes down to being able to capture blocks of code and their context to be referenced at some point later on and executed when/if/as required.

They may not seem to be a big deal, and closures definitely aren't something you need to get things done on a daily basis - but they can make code code much simpler and cleaner to write/manage.

[edit - code sample based on the comment above]

Java:

List<Integer> numbers = ...;
List<Integer> positives = new LinkedList<Integer>();
for (Integer number : integers) {
    if (number >= 0) {
        positives.add(number);
    }
}

Scala (skipping some of the other niceties like type inference and wildcards so we're only comparing the effect of the closure):

val numbers:List[Int] = ...
val positives:List[Int] = numbers.filter(i:Int => i >= 0)
answered 2009-08-20T11:44:50.353
3

Here are some interesting articles:

answered 2009-08-20T11:47:52.003

Your Answer