For in Groovy

Groovy provides several looping constructs. Here are some basic types of loops.

// The most basic type, with a single condition.
def i = 1
while (i <= 3) {
    println(i)
    i = i + 1
}

// A classic initial/condition/after for loop.
for (int j = 0; j < 3; j++) {
    println(j)
}

// Another way of accomplishing the basic "do this N times" iteration 
// is using the range operator.
(0..2).each { k ->
    println("range $k")
}

// A loop without a condition will repeat indefinitely until you 
// break out of the loop or return from the enclosing method.
while (true) {
    println("loop")
    break
}

// You can also continue to the next iteration of the loop.
(0..5).each { n ->
    if (n % 2 == 0) {
        return // In Groovy, 'return' in a closure is equivalent to 'continue' in a loop
    }
    println(n)
}

When you run this Groovy script, you’ll see the following output:

1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Groovy offers several ways to iterate, including the while loop, traditional for loop, and closure-based iteration methods like each. The range operator (..) is commonly used for iterating over a sequence of numbers.

Unlike Go, Groovy doesn’t have a built-in for loop that can be used without conditions for infinite loops. Instead, you can use while(true) for this purpose.

The continue keyword in Groovy only works in for and while loops. In closure-based iterations (like those using each), you can use return to skip to the next iteration, which behaves similarly to continue.

We’ll see some other loop forms later when we look at collections, closures, and other data structures.