Search code examples
groovy

What does that Groovy constructor like call mean?


Person person = new Person(name: "Fred", age: 42)

What does that Groovy syntax mean ? Is this a call to init a Person constructor ? What if Person class has another attribute address and occupation. Will Person(name: "Fred", age: 42) still work ?

Is there a dokumentation on this ?


Solution

  • Let's assume you have this class:

    class Person {
      String name
      int age
      String phoneNumber = "none"
      int areaCode = 0
    }
    

    If you create a person like:

    Person person = new Person(name: "Fred", age: 42)
    println person.phoneNumber // will be "none"
    println person.areaCode // will be 0
    

    If you create a person like:

    Person person = new Person(phoneNumber: "1-222-333-444", areaCode: 10)
    println person.name // will be null (not empty, as no default value exists)
    println person.age // will be 0 (as int is primitive data type)
    

    In summary, any field that you don't specify, will have its default value.