Loops

The loops of Java all work, and the GDK adds a method for the most common shape: do this for every element. The course writes the method when the index and the counter are not needed, because it is shorter and cannot run past the end.

for and while

loops.groovy

for (int i = 1; i <= 3; i++) { println "for ${i}" } def names = ['Ada', 'Grace'] for (name in names) { println "name ${name}" } int count = 3 while (count > 0) { println "while ${count}" count-- } int once = 1 do { println "do ${once}" once++ } while (once < 2)

groovy loops.groovy

for 1
for 2
for 3
name Ada
name Grace
while 3
while 2
while 1
do 1

for (name in names) is the Groovy spelling of a for-each; the type of name is the type of the element. do-while runs its body before the first test, which is the difference from while.

each, eachWithIndex and times

each.groovy

def letters = ['a', 'b', 'c'] letters.each { println "each ${it}" } letters.eachWithIndex { letter, index -> println "${index}: ${letter}" } 3.times { println "times ${it}" } def ages = [ada: 36, grace: 85] ages.each { name, age -> println "${name} is ${age}" }

groovy each.groovy

each a
each b
each c
0: a
1: b
2: c
times 0
times 1
times 2
ada is 36
grace is 85

each passes the element to the closure; a two-parameter closure on a map receives the key and the value. times counts from zero, which is why it suits a repeat with no data.

Stopping early

stop.groovy

def numbers = 1..10 println numbers.find { it > 3 } println numbers.findAll { it % 2 == 0 } println numbers.any { it > 9 } println numbers.every { it > 0 } for (int n in numbers) { if (n == 4) { break } println n }

groovy stop.groovy

4
[2, 4, 6, 8, 10]
true
true
1
2
3

A loop over a range stops with break, and a continue skips one turn. A GDK search does not need a loop at all: find stops at the first match, any answers whether one element matches, and every whether all do.

return inside a closure leaves that turn of the closure and not the method around it, which is the difference between a closure and a block of a loop.

Related

Автор статьи: Arthur Isaev