Ranges in Groovy

Ranges is one of the types of data that you can work with in Groovy that can be used to store list of values or sequence of values. For example: numbers from 1 to 10 or alphabets from A to Z. Ranges in Groovy are implemented as Interfaces. A range is usually denoted by the first and last value of the sequence and there are 2 types of ranges in Groovy.

Types of Ranges:

  • Exclusive Range
  • Inclusive Range

Following are some of the examples for Ranges:

  • Inclusive Range: 1..5
  • Exclusive Range: 1..<5
  • Descending order Range: 5..1
  • Ranges can contain alphabet characters: ‘a’..’z’
  • Descending order Range with alphabet characters: ‘z’..’a’

Lets write a quick code for an example Range:

Range myRange = 1..5
println myRange
println myRange.class.name

Following is the output of the above code:

Groovy Range Code Output and IntRange

If you see the output it prints the range of values from 1 to 5 and the class name being printed is “groovy.lang.IntRange”. IntRange is one of the Interface of Ranges. And now lets replace the range code from integer to alphabets:

Range myRange = 'a'..'z'
println myRange
println myRange.class.name

and the output would be range of alphabets printed from a to z and the class name printed would be of type “groovy.lang.ObjectRange”. Thus there are different Interfaces for Ranges.

Groovy Object Range Output

Following are some of the methods that you can apply on the Ranges object:

  • getFrom() – to get the starting value of the Range
  • getTo() – to get the ending value of the Range
  • get() – to get a particular value in the Range
  • contains() – check if a particular value exists within the Range
  • size() – to get the size or count of values in the Range
  • subList() – to get the +
  • isReverse() – to check if the Range is a Reversed Range (values are in reverse order)

Ranges are basically objects and that’s the reason why we are able to call methods on them.

Related Posts