Skip to main content

Is closure swing ?

Posted by forax on August 29, 2006 at 4:08 PM PDT

Yes, this is another entry about closure :)

In the closure proposal, the section "Closure conversion"
describes how to use a closure instead of an anonymous class.


The rules are :

  • the implemented interface must have one method
  • the closure signature must be a subtype of the method signature



So let see if these rules are sufficient to use closures in order to
implement AWT/Swing callbacks.

 

Implementing an ActionListener

ActionListener corresponds to a component default action,
it's a one method interface, the method actionPerformed takes
an ActionEvent that contains among other things the component
that received the event.

  public interface ActionListener {
    void actionPerformed(ActionEvent e);
  }

So the client code can be this one :

 JButton button=new JButton("Ok");
button.addActionListener(() {
   button.setText("Ko");
});

Oh no !!!


This code is too optimistic, it assumes that because the event
is not used, the parameter can be omit. But there is no such rule
in the proposal. The correct code is the following :

 JButton button=new JButton("Ok");
button.addActionListener((ActionEvent notUsed) {
   button.setText("Ko");
});

The moral

It could be a good idea to add a closure conversion rule that permits
parameters omission. Perhaps this rule can be extended
to allow the omission of the last parameters from the right.

What do you think about that ?

Related Topics >>