Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Classes and Traits

Constructors and Named Arguments

Learn how Groovy objects are created: the default map-based constructor, explicit constructors, positional arguments, list coercion with as, initializer blocks, and @TupleConstructor.

Creating objects in Groovy can be done in several ways, from Java-style constructors to named arguments that read like a configuration. This lesson covers each, explains the rules that decide which one Groovy uses, and shows how to keep construction safe with validation and defaults.

Groovy code is read-only here; Java stand-ins use records and builders that you can run.

The default constructor with named arguments

If a class declares no constructor, Groovy gives you a no-argument constructor and allows named arguments that call the setters:

GROOVY
class Book {
    String title
    String author
    int pages = 100          // default value
}

def b = new Book(title: 'Dune', author: 'Frank Herbert')
println "$b.title by $b.author, $b.pages pages"   // Dune by Frank Herbert, 100 pages

def empty = new Book()
println empty.title                               // null

What actually happens: Groovy calls new Book() and then, for each name in the map [title: 'Dune', author: '...'], calls the setter (or sets the property). That is why it works only when a no-argument constructor exists and the named arguments match property names. An unknown name throws MissingPropertyException.

GROOVY
new Book(titel: 'typo')    // MissingPropertyException: No such property: titel

This readability is a major reason why Groovy test data and configuration code look so clean.

Writing your own constructors

Define constructors as in Java. Once you add one, the automatic no-argument constructor (and the named-argument call) no longer exists unless you also write a no-argument constructor:

GROOVY
class Point {
    int x, y

    Point(int x, int y) {
        this.x = x
        this.y = y
    }

    Point() { this(0, 0) }        // delegate to the main constructor
}

def a = new Point(3, 4)
def origin = new Point()
println "${a.x},${a.y}"

Constructors may call this(...) or super(...) as the first statement. Parameters can have default values, which generate overloads:

GROOVY
class Server {
    String host
    int port

    Server(String host = 'localhost', int port = 8080) {
        this.host = host
        this.port = port
    }
}
println new Server().port           // 8080
println new Server('example.org').host  // example.org

The Java stand-in uses a record with a compact constructor to validate and several factory methods for the defaults.

Java Java stand-in: defaults and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Positional arguments and list coercion

A constructor call like new Point(3, 4) is positional. Groovy also lets you build an object from a list with as, or by assigning a list to a typed variable:

GROOVY
Point p1 = [3, 4] as Point
Point p2 = [3, 4]             // implicit coercion in a typed assignment
def p3 = [x: 1, y: 2] as Point   // map coercion uses named arguments

This feature is called coercion. It means Point[] points = [[0, 0], [1, 1]] works, and a method draw(Point p) accepts draw([1, 2]). Use it sparingly; it hides the type, but for small value classes it makes data definitions compact.

Initialization order

When you create an object, things run in this order:

  1. Field default values and instance initializer blocks { ... } in the order written.
  2. The constructor body.
  3. For named-argument creation: the setter calls, after the no-argument constructor completes.
GROOVY
class Counter {
    int count = 5
    { count += 1 }                      // instance initializer
    Counter() { count *= 2 }
}
println new Counter().count            // 12

The result is 12: the field starts at 5, the initializer makes it 6, and the constructor doubles it. Static fields and static { } blocks run once when the class loads.

Immutable objects with final properties

A final property has no setter and must be set in a constructor:

GROOVY
class Coordinate {
    final double lat
    final double lon

    Coordinate(double lat, double lon) {
        this.lat = lat
        this.lon = lon
    }
}
def c = new Coordinate(51.5, -0.12)
// c.lat = 0     // ReadOnlyPropertyException

Final properties make the object safe to share between threads. The @Immutable annotation takes this idea further (AST Transformations).

Generating constructors with @TupleConstructor

Writing this.x = x lines is the kind of boilerplate Groovy dislikes, so an AST transformation does it for you:

GROOVY
import groovy.transform.TupleConstructor

@TupleConstructor
class Employee {
    String name
    int salary = 3000
}

def e1 = new Employee('Ada')            // salary keeps its default
def e2 = new Employee('Bob', 4200)
println "$e1.name $e1.salary"           // Ada 3000

@TupleConstructor creates a constructor with one parameter per property, in declaration order, and each property with a default value becomes an optional parameter. Options include includes, excludes, callSuper and includeFields. If you also want a no-argument constructor, add @MapConstructor or the combined @Canonical.

Named arguments in ordinary methods

When a method's first parameter is a Map, Groovy collects named arguments into it:

GROOVY
def connect(Map options, String url) {
    def timeout = options.timeout ?: 30
    "connect $url with timeout $timeout, retries ${options.retries ?: 0}"
}

println connect('http://x.test', timeout: 10, retries: 3)

The call passes timeout: 10, retries: 3 first, then the string: Groovy moves named arguments into the leading Map parameter. This is how many Groovy libraries offer optional settings without overload explosions.

The builder alternative

When an object has many optional parts, a builder keeps construction readable. Groovy's own @Builder annotation (from groovy.transform.builder) generates a fluent builder: Person.builder().name('Ada').age(36).build(). See AST Transformations.

Java Java stand-in: a hand-written fluent builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does new Book(title: 'Dune') do when Book has no explicit constructor?

    Groovy creates the object with the default constructor and then assigns each named property through its setter.
  2. 2. After you write Point(int x, int y) { ... }, what happens to new Point(x: 1, y: 2)?

    The named-argument form needs a no-argument constructor. Declaring any constructor removes the implicit one.
  3. 3. Which annotation generates a constructor with one parameter per property?

    @TupleConstructor creates the positional constructor, with default-valued properties becoming optional.
  4. 4. A method def f(Map opts, String s) is called as f('x', a: 1). How does Groovy treat a: 1?

    Named arguments are gathered into the first Map parameter, whatever their position in the call.

Summary

  • Without constructors, new T(name: value) calls the no-arg constructor and sets properties.
  • Declaring a constructor removes the implicit one; default parameter values create overloads.
  • as and typed assignment can coerce lists and maps into objects.
  • @TupleConstructor and @Builder remove boilerplate; final properties give immutability.
  • Methods with a leading Map parameter accept named arguments.

Next: Inheritance and Interfaces