Skip to Content »

Tech Life of Recht » archive for 'closures'

 Implementing closures in Java

  • February 23rd, 2008
  • 1:40 pm

There's been a lot of discussion about how to include closures in Java7, and whether they should be included at all or not. Everybody seems to agree that Java already has the poor man's version of closures: anonymous inner classes.
Here's my proposal on how to implement "real" closures: create a folding plugin for Eclipse, Netbeans, IntelliJ which simply folds

CODE:
  1. JButton b = new JButton("press me");
  2. b.addActionListener(new ActionListener() {
  3.   public void actionPerformed(ActionEvent e) {
  4.     System.out.println(e);
  5.   }
  6. });

into

CODE:
  1. JButton b = new JButton("press me");
  2. b.addActionListener(ActionEvent e -> { System.out.println(e) });

Syntax borrowed from Groovy, but any would do. 100% backwards compatibility for free, no compiler modifications needed, support for all Java versions, just with a couple of plugins. Yes, it's cheating, but I don't care, it's been years since I wrote a line of Java code without Eclipse or something like it.

I would do it myself, but I my backlog of ideas to implement is big enough as it is, so if someone else should have the time, please go ahead.