Groovy is known for exending standard Java classes with extra methods or extra arguments for existing methods. Since Groovy 5 you can use a range as argument for the List.subList method. The range is used to determine the begin and end index of the original List instance to return.

In the following example code several range values are used with the subList method:

def languages = ['Groovy', 'Kotlin', 'Clojure', 'Java', 'Frege']

// The standard Java subList method takes two arguments
// with the begin and end index (exclusive) to return
assert languages.subList(0, 2) == ['Groovy', 'Kotlin']

// Groovy adds support for a range as argument to subList.
// Notice the range is inclusive.
assert languages.subList(0..2) == ['Groovy', 'Kotlin', 'Clojure']
assert languages.subList(0..1) == ['Groovy', 'Kotlin']

// You can specify an exclusive range.
assert languages.subList(0..<2) == ['Groovy', 'Kotlin']
assert languages.subList(1<..<3) == ['Clojure']

// A range can also be defined in descending order.
assert languages.subList(4..2) == ['Clojure', 'Java', 'Frege']

Written with Groovy 5.0.0.

shadow-left