Skip to main content

Closure Litteral and Method Reference

Posted by forax on February 27, 2007 at 3:46 AM PST

Recently, Stephen Colebourne and Stefan Schulz post another closure like proposal, yes, yet another one.

They propose another syntax for describing a closure
which, in my opinion, is more a simpler way
to declare an inner-class.

I am not a big fan of this proposal,
i definitively prefer the
closure syntax
decribed by Neal Gafter.

But there is something that i like in their proposal,
the fact that you can create invocable method references.

Invocable Method Reference

We need a way to easily create a reference to a method,
an object that allow to call a method.
Currently a method is not an Object
and if you want something like that
you have to use reflection (java.lang.reflect.Method)
which is not type-safe, uses lot of checked exceptions
and performs primitive boxing and array boxing.

So having a way to create a method reference is a good think.
But unlike Stephen and Stefan, i don't think that
a method reference is a java.lang.reflect.Method correctly typed
by the compiler but instead a java.function object (a closure)
of Neal.

In my opinion method reference is a kind of closure litteral,
so this code snippet:

  public void init() {
    JButton button = ...;
  public void handleAction(ActionEvent ev) {
    // handle event

is a short syntax for:

  public void init() {
    JButton button = ...;
    button.addActionListener({ActionEvent e=>
  public void handleAction(ActionEvent ev) {
    // handle event

Because a method reference is a closure litteral,
the type of a method reference is a function type.

 {ActionEvent=>void} handle = this#handleAction(ActionEvent);

I think that using # is a good idea.
Perhaps because it's the syntax i choose to use
to create property litteral (property reference)
in my next property proposal that
i will post in few days.

Cheers, R

Related Topics >>