Constructors and named parameters
A class with no constructor gets two: a no-arg one and one that takes a map of property names. That second one is what a named-argument call uses, and it disappears as soon as the class declares a constructor of its own.
The constructor a class gets free
free.groovy
class Book {
String title
int pages
}
def a = new Book(title: 'Groovy', pages: 120)
def b = new Book()
println a.title
println b.pages
println Book.constructors*.parameterTypes*.simpleName
groovy free.groovy
Groovy
0
[[]]
The last line lists the constructors the compiler added. The map form is not a real signature: Groovy takes the named arguments, calls the no-arg constructor and sets each property.
A declared constructor
declared.groovy
class Book {
String title
int pages
Book(String title) {
this.title = title
}
}
println new Book('Groovy').title
try {
new Book(title: 'Named')
} catch (GroovyRuntimeException error) {
println error.message
}
groovy declared.groovy
Groovy
Could not find named-arg compatible constructor. Expecting one of:
Book(Map)
Book()
With one constructor declared, the no-arg one and the named-argument path are gone. A class that needs both writes a no-arg constructor, or takes the named parameters itself:
mapctor.groovy
class Book {
String title
int pages
Book(Map values) {
this.title = values.title
this.pages = values.pages ?: 0
}
}
def book = new Book(title: 'Groovy')
println book.title
println book.pages
groovy mapctor.groovy
Groovy
0
The map constructor is the explicit form of the same thing, with the defaults a caller needs. ?: gives pages a value when the map has none.
What @CompileStatic changes
staticctor.groovy
import groovy.transform.CompileStatic
@CompileStatic
class Point {
int x
int y
}
println Point.constructors*.parameterTypes*.simpleName
groovy staticctor.groovy
[[]]
A statically compiled class keeps the no-arg constructor and no map form, because the compiler has to know the call at compile time. Give it @TupleConstructor (the next lesson) for positional arguments, or write the constructor.
Related
- The AST transforms of a data class: @TupleConstructor in full.
- @CompileStatic and @TypeChecked: the price of the static check.
Article author: Arthur Isaev