Working with maps and properties
Maps and properties are data structures in Groovy that provide a way to store key-value pairs, similar to dictionaries or associative arrays in other programming languages.
Maps: Maps in Groovy are created using curly braces and colons:
pythonCopy codedef capitals = [USA: "Washington DC", France: "Paris", Germany: "Berlin"] println capitals.USA // outputs: "Washington DC"Maps in Groovy are dynamic, so you can add or remove elements from them at any time:
javaCopy codedef capitals = [USA: "Washington DC", France: "Paris", Germany: "Berlin"] capitals.Spain = "Madrid" println capitals // outputs: [USA:Washington DC, France:Paris, Germany:Berlin, Spain:Madrid]Properties: Properties in Groovy are similar to maps, but provide a convenient syntax for working with object properties. Properties can be defined using the
def
keyword:pythonCopy codeclass Person { def name } def john = new Person(name: "John Doe") println john.name // outputs: "John Doe"Properties in Groovy are dynamically typed, so you can assign values of any type to them:
rubyCopy codeclass Person { def name def age } def john = new Person(name: "John Doe", age: 30) println john.age // outputs: 30
These are just a few examples of the power and flexibility of maps and properties in Groovy. With these tools, you can write code that is easy to read, write, and maintain, making Groovy a great choice for many types of projects.
Leave a Comment