Close

Groovy Operators - Subscript Operator

[Last Updated: Jan 22, 2019]

Subscript operator ([]) allows to read/write collections and maps. We can also define custom object which is to be used with the subscript operator.

Examples

src/Example1List.groovy

def list = [2, 4]

println list[0] //reading
list[0] = 1//writing
println list

Output

2
[1, 4]

src/Example2Map.groovy

def map = [x: 2, y: 4]
println map['x'] //reading
map['x'] = 1//writing
println map

Output

2
[x:1, y:4]

With Range operator

Subscript operator can be used with range operator to read or write to a collection:

src/Example3WithRange.groovy

def list = [2, 4, 6, 8]
def list2 = list[0..2]// reading
println list2
list[0..3] = [1, 3, 5, 7] //replacing elements
println list
list[4..7] = [9, 11, 13] //adding new elements
println list

Output

[2, 4, 6]
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]

Custom object for subscript operator

We need to implement getAt/putAt methods so that it can be used with the subscript operator:

src/Example4Custom.groovy

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name
        this.age = age
    }

    def getAt(int i) {
        switch (i) {
            case 0: return name
            case 1: return age
        }
    }

    void putAt(int i, def value) {
        switch (i) {
            case 0: name = value; break
            case 1: age = value; break
        }
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

def p = new Person("Mike", 31);
println p[0] // reading
println p[1] // reading
p[0] = "Sara" // writing
p[1] = 25

Output

Mike
31
Person{name='Sara', age=25}

Above behavior is also called destructuring of objects.

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 9.0.1
Groovy - Subscript Operator Select All Download
  • groovy-subscript-operator
    • src
      • Example1List.groovy

    See Also