Reading — step 1 of 5
Learn
~1 min readBeans and Errors
A GroovyBean is a class with simple properties — Groovy auto-generates getters and setters. Like Lombok in Java, but built in.
class Person {
String name
int age
boolean active = true // default value
}
def p = new Person(name: "Ada", age: 36) // constructor takes named args
p.name = "Ada Lovelace" // setter — under the hood: p.setName(...)
println p.name // getter — under the hood: p.getName()
The field declaration is short — Groovy generates the getter/setter, the no-arg constructor, the named-arg constructor, all behind the scenes.
@Canonical auto-generates equals, hashCode, toString, and a positional constructor:
import groovy.transform.Canonical
@Canonical
class Point {
int x
int y
}
def p1 = new Point(3, 4) // positional — works because of @Canonical
println p1 // "Point(3, 4)"
p1 == new Point(3, 4) // true
@Immutable — like @Canonical but freezes the object:
@Immutable
class Point { int x, int y }
@ToString(includeNames=true) — controls toString format:
@ToString(includeNames=true)
class User { String name; int age }
// User(name:Ada, age:36)
All of these are AST transformations — applied at compile time, no runtime cost.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…