concept range in category groovy

appears as: rges, range, rge, A rge, rge
Groovy in Action, Second Edition

This is an excerpt from Manning's book Groovy in Action, Second Edition.

Although ranges don’t appear in the standard Java libraries, most programmers have an intuitive idea of what a range is—effectively a start point and an end point, with an operation to move between the two in discrete steps. Again, Groovy provides literals to support this useful concept, along with other language features such as the for statement, which understands ranges.

The following code demonstrates the range literal format, along with how to find the size of a range, determine whether it contains a particular value, find its start and end points, and reverse it:

Groovy allows you to reveal the meaning of such code pieces by providing the concept of a range. A range has a left bound and a right bound. You can do something for each element of a range, effectively iterating through it. You can determine whether a candidate element falls inside a range. In other words, a range is an interval plus a strategy for how to move through it.

By introducing the new concept of ranges, Groovy extends your means of expressing your intentions in the code.

We’ll show you how to specify ranges, how the fact that they’re objects makes them ubiquitously applicable, how to use custom objects as bounds, and how they’re typically used in the GDK.

4.1.2. Ranges are objects

Because every range is an object, you can pass a range around and call its methods. The most prominent methods are each, which executes a specified closure for each element in the range, and contains, which specifies whether or not a value is within a range.

Being first-class objects, ranges can also participate in the game of operator overriding (see section 3.3) by providing an implementation of the isCase method, with the same meaning as contains. That way, you can use ranges as grep filters and as switch cases. This is shown in the following listing.

Listing 4.2. Ranges are objects

The ..< range operator specifies a half-exclusive range—that is, the value on the right isn’t part of the range:

left..right
(left..right)
(left..<right)

Ranges usually have a lower left bound and a higher right bound. When this is switched it’s called a reverse range. Ranges can also be any combination of the types we’ve described. The following listing shows these combinations and how ranges can have bounds other than integers, such as dates and strings. Groovy supports ranges at the language level with the special for-in-range loop.