クロージャが使えると、RubyとかjQueryでよくやるあの感じ(笑)のコーディングが出来る!
説明ができないので、コード書きます。
スコープ
クロージャはブロックの外側の変数にアクセスすることができる。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = "xxx" | |
c = { | |
a = it | |
b = it | |
println a | |
} | |
c("o_o") | |
println a | |
println b | |
/* | |
o_o | |
o_o | |
o_o | |
*/ |
レキシカルスコープ
クロージャが呼び出された場所ではなく、クロージャが宣言されている場所からみたスコープが有効
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.e2info.groovy | |
if(true){ | |
def a = 123 | |
b = {print a} | |
} | |
if(true){ | |
def a = 456 | |
b.call(); | |
} | |
/* | |
123 | |
*/ |
変数の束縛
クロージャ内で宣言した変数のスコープはクロージャ内のみとなる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.e2info.groovy | |
a = "xxx" | |
def c = { | |
def a = "x_x" | |
return { println a } | |
}() | |
a = "xxx" | |
println a | |
c() | |
/* | |
xxx | |
x_x | |
*/ |
本領発揮
必殺!この記法で書くことができると、イテレーションの条件と実際の処理を分離することができる。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.e2info.groovy | |
[1, 2, 3, 4].each({x -> println x}) | |
/* | |
1 | |
2 | |
3 | |
4 | |
*/ |
どんどんつかおうクロージャ!
かねこ( ゚ ρ ゚ )
0 件のコメント:
コメントを投稿