Last published: 12 March 2004 |
Using Groovy
User Guide
Articles
|
Groovy supports the usual while {...} and do {...} while loops like Java. x = 0 y = 5while ( y-- > 0 ) { x++ }assert x == 5x = 0 y = 5do { x++ } while ( --y > 0 )assert x == 5 The for loop in Groovy is much simpler and works with any kind of array, collection, Map etc. // iterate over a range x = 0 for ( i in 0..9 ) { x += i } assert x == 45// iterate over a list x = 0 for ( i in [0, 1, 2, 3, 4] ) { x += i } assert x == 10// iterate over an array array = (0..4).toArray() x = 0 for ( i in array ) { x += i } assert x == 10// iterate over the characters in a string text = "abc" list = [] for (c in text) { list.add(c) } assert list == ["a", "b", "c"] |
© 2003-2004, The Codehaus |