Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Excerpt
hiddentrue

Groovy supports the usual while {...} loops like Java.


GroovyはJavaのように通常のwhile {...} のループをサポートします。

Code Block
def x = 0
def y = 5

while ( y-- > 0 ) {
    x++
}

assert x == 5

Excerpt
hiddentrue

for loop

forループ

Excerpt
hiddentrue

The for loop in Groovy is much simpler and works with any kind of array, collection, Map etc.
Note: the standard for loop is not implemented by beta-10.
// for (int i = 0; i < 5; ++i) // not implemented by beta-10.


Groovyのforフープはかなりシンプルで、配列、コレクション、Mapなどが使えます。
注意: 標準のforループはbeta-10まで実装されていませんでした。
// for (int i = 0; i < 5; ++i) // はbeta-10まで実装されていませんでした。
Excerpt
hiddentrue

// iterate over a range

Excerpt
hiddentrue

// iterate over a list

Excerpt
hiddentrue

// iterate over an array

Excerpt
hiddentrue

// iterate over a map

Excerpt
hiddentrue

// iterate over values in a map

Excerpt
hiddentrue

// iterate over the characters in a string

Code Block
// Rangeの終わりまで繰り返す
def x = 0
for ( i in 0..9 ) {
    x += i
}
assert x == 45

// Listの終わりまで繰り返す
x = 0
for ( i in [0, 1, 2, 3, 4] ) {
    x += i
}
assert x == 10

// 配列の終わりまで繰り返す
array = (0..4).toArray()
x = 0
for ( i in array ) {
    x += i
}
assert x == 10

// Mapの終わりまで繰り返す
def map = ['abc':1, 'def':2, 'xyz':3]
x = 0
for ( e in map ) {
    x += e.value
}
assert x == 6

// Mapのvalueを終わりまで繰り返す
x = 0
for ( v in map.values() ) {
    x += v
}
assert x == 6

// String内の文字(char)を終わりまで繰り返す
def text = "abc"
def list = []
for (c in text) {
    list.add(c)
}
assert list == ["a", "b", "c"]

Excerpt
hiddentrue

closures

クロージャ

Excerpt
hiddentrue

In addition, you can use closures in place of most for loops, using each() and eachWithIndex():


ほとんどの場合、each()やeachWithIndex()を使うことでforループの換わりにクロージャを使うことが出来ます。

Code Block
def stringList = [ "java", "perl", "python", "ruby", "c#", "cobol",
                   "groovy", "jython", "smalltalk", "prolog", "m", "yacc" ];

def stringMap = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday",
                  "We" : "Wednesday", "Th" : "Thursday", "Fr" : "Friday",
                  "Sa" : "Saturday" ];

stringList.each() { print " ${it}" }; println "";
// java perl python ruby c# cobol groovy jython smalltalk prolog m yacc

stringMap.each() { key, value -> println "${key} == ${value}" };
// Su == Sunday
// We == Wednesday
// Mo == Monday
// Sa == Saturday
// Th == Thursday
// Tu == Tuesday
// Fr == Friday

stringList.eachWithIndex() { obj, i -> println " ${i}: ${obj}" };
// 0: java
// 1: perl
// 2: python
// 3: ruby
// 4: c#
// 5: cobol
// 6: groovy
// 7: jython
// 8: smalltalk
// 9: prolog
// 10: m
// 11: yacc

stringMap.eachWithIndex() { obj, i -> println " ${i}: ${obj}" };
// 0: Su=Sunday
// 1: We=Wednesday
// 2: Mo=Monday
// 3: Sa=Saturday
// 4: Th=Thursday
// 5: Tu=Tuesday
// 6: Fr=Friday