Sunday 27 January 2019

Groovy: Map: Access the keys using . notation


If the keys are strings, you can access them using '.' operator.

HelloWorld.groovy
def employee = ['id' : 123, 'name' : 'Krishna', 'age' : 29]

println "id : ${employee.id}"
println "name : ${employee.name}"
println "age : ${employee.age}"

Output
id : 123
name : Krishna
age : 29

You can even use '.' operator to update the values.


HelloWorld.groovy
def employee = ['id' : 123, 'name' : 'Krishna', 'age' : 29]
printEmployeeDetails(employee)

employee.id = 456
employee.name = 'Aakash'
employee.age = 31

println "\nData after updating the fields\n"

printEmployeeDetails(employee)

void printEmployeeDetails(emp){
 println "id : ${emp.id}"
 println "name : ${emp.name}"
 println "age : ${emp.age}"
}

Output
id : 123
name : Krishna
age : 29

Data after updating the fields

id : 456
name : Aakash
age : 31




Previous                                                 Next                                                 Home

No comments:

Post a Comment