Thursday, 17 January 2019

Groovy: Subscript Operator


Subscript operator is used to get the element of an array at specific index and set the element of array at given index.

HelloWorld.groovy
def arr1 = [2, 3, 5, 7, 11, 13, 17, 19]

println "arr1[0] ${arr1[0]}"
println "arr1[3] ${arr1[3]}"
println "arr1[5] ${arr1[5]}"

println "\nSetting the values at 0 to 100, 3 to 101, 5 to 102\n"

arr1[0] = 100
arr1[3] = 101
arr1[5] = 102

println "arr1[0] ${arr1[0]}"
println "arr1[3] ${arr1[3]}"
println "arr1[5] ${arr1[5]}"


Output
arr1[0] 2
arr1[3] 7
arr1[5] 13

Setting the values at 0 to 100, 3 to 101, 5 to 102

arr1[0] 100
arr1[3] 101
arr1[5] 102

By providing getAt, setAt methods you can use subscript [] operator on custom types.


HelloWorld.groovy
class Employee{
 int id
 String firstName
 String lastName
 
 def getAt(int i) {                                             
  switch (i) {
   case 0: return id
   case 1: return firstName
   case 2: return lastName
        }
  throw new IllegalArgumentException("No such element $i")
    }
 
    void putAt(int i, def value) {                                 
  switch (i) {
   case 0: id = value; return
            case 1: firstName = value; return
   case 2: lastName = value; return
        }
        throw new IllegalArgumentException("No such element $i")
    }
}

Employee emp1 = new Employee()
emp1[0] = 123
emp1[1] = "Krishna"
emp1[2] = "Gurram"

println "emp1[0] : ${emp1[0]}, emp1.id : ${emp1.id}"
println "emp1[1] : ${emp1[1]}, emp1.firstName : ${emp1.firstName}"
println "emp1[2] : ${emp1[2]}, emp1.lastName : ${emp1.lastName}"

Output
emp1[0] : 123, emp1.id : 123
emp1[1] : Krishna, emp1.firstName : Krishna
emp1[2] : Gurram, emp1.lastName : Gurram


Previous                                                 Next                                                 Home

No comments:

Post a Comment