Tonight I went to a PittJUG meeting on Closures. Neal Gafter from Google gave a
great talk. You could tell he'd done it before and that he really
cared about it, and also that he was barely scratching the surface and
could talk about this for many more hours. (And that he'd love to do
so!)
Some notes from the talk:
- Same talk as @ JavaOne
- been working on this for ~ year
- what are they? why do you want to do this? what does it add?
- MJD quote about laughing at languages without closures
- Goals:
declare: withLock( someLock, someCode ); (not shown, spoken)
usage: withLock( getLock ) {
fee();
fi();
fo();
} <-- look! no semicolon after the block
Closure expressions:
{ [ parameter declarations ] => [block statements] [expression] }
- object that represents code + lexical context
- may return from enclosing method
- Closure conversion: compiler figures out at compile time what
type the closure is: if it's a no-arg closure that returns
nothing, it can be taken as a Runnable
- Can be cases where the closure can match multiple overloaded
methods, but he only found one case in the JDK where this would
have happened (in Executor stuff)
- Possible for API author to restrict what the closures can do (no
non-local returns when the calling context doesn't exist later)
- If no 'target type', assumes a 'natural function type'
Function types:
{ [ parameter declarations ] => return type [ throws ... ] }
- parameters and return values can be generics
- these aren't required, can still use interfaces to declare what
the function does (better when they're named)
</ul>
{ String => int throws NumberFormatException}
becomes
java.lang.function.IO<String,NumberFormatException>
^^ I = int, O = Object
or
package java.lang.function;
public interface IO<A, X extends Exception> {
int invoke( A arg ) throws X;
^^^^^^always named invoke (like proxies)
}
- Function interfaces are generated by javac at runtime, won't find in JDK.
Finally:
- Lots of examples (before/after)
- Easy to digest classes of items that this can be used for:
- Locking
- More iterations (for eachEntry( Key, Value : map ))
- Closeables (streams, DB connections)
</li>
- Others:
- Fork/Join Concurrency (Doug Lea, exists now but no good way to express)
- Higher order utilities
- AOP? (register advice and cutpoints, then match them up at runtime)
- Continuations? (bounded continuations...)
- Multiple dispatch?
Homepage of closures proposal:
http://www.javac.info/