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.groovydef list = [2, 4]
println list[0] //reading
list[0] = 1//writing
println list Output2 [1, 4]
src/Example2Map.groovydef map = [x: 2, y: 4]
println map['x'] //reading
map['x'] = 1//writing
println map Output2 [x:1, y:4]
With Range operator
Subscript operator can be used with range operator to read or write to a collection:
src/Example3WithRange.groovydef 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.groovyclass 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 OutputMike 31 Person{name='Sara', age=25}
Above behavior is also called destructuring of objects.
Example ProjectDependencies and Technologies Used: |
|