Show List

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.

  1. Maps: Maps in Groovy are created using curly braces and colons:

    python
    Copy code
    def 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:

    java
    Copy code
    def capitals = [USA: "Washington DC", France: "Paris", Germany: "Berlin"] capitals.Spain = "Madrid" println capitals // outputs: [USA:Washington DC, France:Paris, Germany:Berlin, Spain:Madrid]
  2. 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:

    python
    Copy code
    class 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:

    ruby
    Copy code
    class 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


  • captcha text