Skip to content
Loops
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow

Standard for and while work like Java. Idiomatic Groovy uses collection methods instead:

for (i in 1..5) println i              // 1, 2, 3, 4, 5
for (item in ["a", "b", "c"]) println item

5.times { println it }                  // 0, 1, 2, 3, 4
(1..10).each { println it }
(1..5).step(2) { println it }           // 1, 3, 5

Ranges are first-class:

def r = 1..10                           // inclusive
def e = 1..<10                          // exclusive end (1..9)
def d = 10..1                           // descending
r.size()                                 // 10
r.contains(5)                            // true

while for unknown-iteration loops:

def n = 1
while (n < 100) n *= 2

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…