Created
November 6, 2011 01:16
-
-
Save mike-neck/1342315 to your computer and use it in GitHub Desktop.
Closureをいじってみた https://gist.github.com/1342315 written by @mike_neck #gdk48 #jggugcamp
This file contains 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
println 'Closure のおもろいところ' | |
println '基本' | |
[1,2,3,4].each { println it } | |
println 'オブジェクトのプロパティを表示する' | |
class Person { | |
def firstName | |
def middleName | |
def lastName | |
def age | |
def address | |
@Override each(Closure clsr) { | |
[this.firstName, this.middleName, this.lastName, this.age, this.address].each {clsr(it)} | |
} | |
} | |
def mike = new Person(firstName : 'mike', middleName : '_', lastName : 'neck', age : 34, address : '野良') | |
def list = [] | |
mike.each { list << it } | |
list.sort().each {println it} | |
println 'Closure を別で定義する' | |
def clsr = { | |
println it | |
} | |
[1,2,3,4].each(clsr) | |
println 'Closure を返す(1)' | |
Integer.metaClass.define { | |
closure {int arg -> | |
return {delegate + arg as int} | |
} | |
} | |
int my = 10 | |
println 10.closure(1)().closure(1)().closure(1)() | |
println 'Closure を返す(2)' | |
Integer.metaClass.define { | |
inc { | |
return { return delegate + 1 as int} | |
} | |
} | |
int inc = 0 | |
println inc.inc()().inc()().inc()().inc()() | |
println 'Closure でClosureを返す(安全)' | |
def counter = { | |
def bs = 0 | |
return {bs++} | |
} | |
def clo1 = counter() | |
def clo2 = counter() | |
10.times{ | |
println clo1() | |
println clo2() | |
} | |
println 'Closure でClosureを返す(安全でない)' | |
def notSafeCounter = { | |
_cnt = 0 | |
return { _cnt++ } | |
} | |
def unSafe1 = notSafeCounter() | |
def unSafe2 = notSafeCounter() | |
10.times { | |
println unSafe1() | |
println unSafe2() | |
} |
This file contains 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
Closure のおもろいところ | |
基本 | |
1 | |
2 | |
3 | |
4 | |
オブジェクトのプロパティを表示する | |
34 | |
_ | |
mike | |
neck | |
野良 | |
Closure を別で定義する | |
1 | |
2 | |
3 | |
4 | |
Closure を返す(1) | |
13 | |
Closure を返す(2) | |
4 | |
Closure でClosureを返す(安全) | |
0 | |
0 | |
1 | |
1 | |
2 | |
2 | |
3 | |
3 | |
4 | |
4 | |
5 | |
5 | |
6 | |
6 | |
7 | |
7 | |
8 | |
8 | |
9 | |
9 | |
Closure でClosureを返す(安全でない) | |
0 | |
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 | |
14 | |
15 | |
16 | |
17 | |
18 | |
19 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment