state-of-the-lambda syntax for non-SAM types such as WindowAdapter.

Reinier Zwitserloot reinier at zwitserloot.com
Thu Jul 8 06:36:35 PDT 2010


Heh, that's a nice trick. There's an alternative version for it that would
work just as well:

public interface WindowListener {
    public abstract class WindowClosed extends WindowAdapter {
        public abstract void windowClosed(WindowEvent e);
    }
}


which re-abstracts windowClosed, turning WindowListener.WindowClosed into a
SAM:

window.addWindowListener(WindowListener.WindowClosed {e -> ...});


between that and your example, this use case is served acceptably.

--Reinier Zwitserloot



On Thu, Jul 8, 2010 at 7:46 AM, Peter Levart <peter.levart at gmail.com> wrote:

> On Thursday, July 08, 2010 05:11:39 am Reinier Zwitserloot wrote:
> > An idea:
> >
> > The state-of-the-lambda document allows lambda literals to be explicitly
> > typed:
> >
> > Comparator<String> {a, b -> return a.length() - b.length()};
> >
> >
> > What if one could also append the method to this? Then these closures can
> > extend to non-SAM types:
> >
> > frame.addWindowListener(WindowAdapter.windowClosed {e -> .... });
> >
> > Just a thought.
> >
> > --Reinier Zwitserloot
>
> You don't need special syntax for that. For example:
>
> public class WindowAdapters
> {
>    interface Fn
>    {
>        void invoke(WindowEvent e);
>    }
>
>    public static WindowAdapter windowOpened(final Fn fn)
>    {
>        return new WindowAdapter()
>        {
>            @Override
>            public void windowOpened(WindowEvent e)
>            {
>                fn.invoke(e);
>            }
>        };
>    }
>
>    public static WindowAdapter windowClosed(final Fn fn)
>    {
>        return new WindowAdapter()
>        {
>            @Override
>            public void windowClosed(WindowEvent e)
>            {
>                fn.invoke(e);
>            }
>        };
>    }
>
>    // etc...
> }
>
>
> // and with an additional pair of parens you can write:
>
> frame.addWindowListener(WindowAdapters.windowClosed({e -> .... }));
>
>
> Regards, Peter
>


More information about the lambda-dev mailing list