For in Groovy
Groovy provides several looping constructs. Here are some basic types of loops.
When you run this Groovy script, you’ll see the following output:
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.