Working with Ranges in Groovy
Ranges are Lists ( java.util.List
) with sequential values. There are two ways you can define Ranges, using ..
this includes the ending value and other way is using ..<
which does not include the ending value. Lets see some examples using a Groovy Program
class RangesInGroovy {
static main(args) {
def rating = 1..5
println rating // prints [1, 2, 3, 4, 5]
println rating.from // prints 1
println rating.to // prints 5
def scale = 1..<10
println scale // prints [1, 2, 3, 4, 5, 6, 7, 8, 9]
println scale.from // prints 1
println scale.to // prints 9
}
}
Ranges are handy to use in for loops
for (i in 1..5) {
println i
}
(1..5).each {
println it
}
Another beautiful thing about Ranges is, they can be used in Switch statement, take a look at following program, where the cases are actually ranges which gives the program more readability
class AgeRanges {
static main(args) {
def input = 15
switch(input) {
case 0..2 : println 'Infant'; break;
case 3..12 : println 'Child'; break;
case 13..59 : println 'Adult'; break;
case 59..100 : println 'Senior Citizen'; break;
default : println 'NA'
}
}
}