Skip to main content

Java Closures: Functions or Objects?

Posted by aschunkjava on January 23, 2008 at 11:56 AM PST

Java Closures? What are they?

The question wheather closures are functions or objects came to my mind when reading several proposals concerning on closures. It looks like most authors regard them as both - functions and objects but giving not a real and concrete distinction in what case a closure is a function - or functional object - and an object.

For example in Neil Gafters vision for closures, closures seem to be both functions or an anonymous function or method and objects - or even classes beecause its possible to extend a class or template from a closure.

I think, if we follow the traditional closure syntax and usage - like in lisp or Perl where closures are regarded as procedures or sub routines. I have difficulties to imag


The disadvantage of the approach BGGA takes is that the following is confusing:

executor.execute( { => ...; } ); // OK


{ => void } toBeRun = { => ...; }; executor.execute( toBeRun ); // Oops

The problem I foresee is that the syntax for a function type is so similar to the syntax for a closure that other people, like myself, will be surprised that the two aren't interchangeable and BGGA could choose to make them interchangeable. Much as a literal 1 (analogous to a closure literal) is interchangeable with an int (analogous to a function type).

A further reason to make function types and closures one in the same, is that as BGGA stands you need function types for recursion:

{ int => int } factorial = { x => x <= 1 ? 1 : x * factorial( x - 1 ) };

Alex, you are mixing up closures and function types. A closure is a block of code (or call it inner method or function) that closes over something (e.g., variables). A function type like Neal defines it is a kind of object oriented helper to enable defining fields, variables, or parameters to take closures as a value. As there is no such thing as a standalone method type for a variable in Java, making instances of anonymous types/classes a container for closures seems rational. In doing so, Java allows for extending such function types as any other type. In Lisp, you don't have types so you don't need to cope with them. In Java (for now) they are mandatory.