Range Over Built in Groovy

Based on the provided Groovy language specification and the Go code example, the translated code and explanation in Groovy will be as follows:

Here we use the each method to sum the numbers in a list. Arrays work like this too.

nums = [2, 3, 4]
sum = 0
nums.each { num ->
    sum += num
}
println "sum: $sum"

each on lists provides both the index and value for each entry. Above we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.

nums.eachWithIndex { num, i ->
    if (num == 3) {
        println "index: $i"
    }
}

each on maps iterates over key/value pairs.

kvs = [a: "apple", b: "banana"]
kvs.each { k, v ->
    println "$k -> $v"
}

each can also iterate over just the keys of a map.

kvs.each { k, v ->
    println "key: $k"
}

each on strings iterates over each character of the string.

"go".eachWithIndex { c, i ->
    println "$i $c"
}
$ groovy rangeOverBuiltInTypes.groovy
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 g
1 o

Next example: Pointers.