12/05/19 21:26:59.53
developerWorksの記事にgroovyのコードがあるんだけど
URLリンク(www.ibm.com)
ここが何をやってるのかわからん
def asSquare(peg) {
[getWidth:{peg.x}] as SquarePeg
}
def asRound(peg) {
[getRadius:{Math.sqrt(((peg.width/2) ** 2)*2)}] as RoundThing
}
[getWidth:{peg.x}] はハッシュオブジェクトなのはわかるが、{peg.x} は関数オブジェクト?
それに as SquarePeg をつけると、
・SquarePegの匿名サブクラスが作られて
・そこに def getWidth() { return peg.x } が定義される
・そしてその匿名サブクラスのインスタンスオブジェクトが作成される
という理解でいいの?
だとすると、getWidth()は引数をとらないメソッドなのに peg という変数を使えるのはなぜ?クロージャだとこういうことができるの?
public SquarePeg asSquare(Peg peg) {
return new SquarePeg() {
public int getWidth() { return peg.x; } // なんで変数pegにアクセスできるの?
};
}