Alex Rivera | Logout

When to use Closures

Asked 2011-06-21T15:23:58.727
13

Note: jump down to "Question" below if you just want to skip the context

When giving talks on Scala I'm almost always certain I'll be asked "but when would you use a Closure?" Typically I say "wait until I show you a for comprehension" and then I show how the for comprehension can be boiled down to using flatMap/map + closures.

This example does help, however it's tough for me to explain a general "this is when you'd recognize when to use a closure". It's one of those things you "just get used to" in functional programming, you almost do it without thinking.

Typically I'm talking to Java devs when I speak about Scala, and one analogy that comes to mind is "you know when you create an anonymous inner class that needs to access a variable somewhere above where the class was defined? That's like a closure". So I use event call-back processing as one particular example (as inevitably you use anonymous inner classes in that scenario).

Considering the audience (no experience, or limited experience with FP) I don't go on to discuss terms like Monads, these people are typically looking for concrete/pragmatic examples they can relate to.

Question: Anyone have their own way of successfully explaining closures that really hits home for Java (or other OO language) developers?

Edit
Report

1 Answer

1

I think you're right on track in relating closures to anonymous inner classes for the sake of introducing the concept to Java developers. I recommend taking some problem that involves heavy use of callbacks, and showing a slide with a side-by-side comparison of the code required in Java using anonymous inner classes and the code required in Scala using closures.

Here are a couple of ideas for problems involving callbacks:

  1. Swing button click handlers
  2. Anything involving a Runnable or Callable (i.e. submitting a task to a ThreadPoolExecutor)
  3. SAX event-based XML parsing
  4. JDBC-based database access code passed through a common transaction executor to cut down on boilerplate connection acquisition/release

For each of these examples, I expect that the Scala/closure solution will turn out shorter and simpler than the Java/anonymous inner class solution.

answered 2011-06-21T16:08:17.773

Your Answer