てきとうなメモ

本の感想とか技術メモとか

Java と Closure

http://gafter.blogspot.com/2006/08/closures-for-java.html

JDK 7 (Dolphin)からClosureを言語として実装するように提案しているようだ.いままでJavaでClosureを使いたい場合は無名のクラスを用いていたが,コードが冗長になるという点と外部の変数はfinal変数しか参照できないという問題があった.

この提案では無名の関数を導入している.例えば2を足す無名の関数は次のように記述できる

int(int) plus2b = (int x) { return x+2; };
// or using the short form
int(int) plus2b = (int x) : x+2;

また,final変数以外の変数も参照できるようになるようだ

Names that are in scope where a function or closure is defined may be referenced within the closure. We do not propose a rule that requires referenced variables be final, as is currently required for anonymous class instances. The constraint on anonymous class instances is also relaxed to allow them to reference any local variable in scope.