Dark theme | Light theme

September 30, 2009

Groovy Goodness: Newify to Create New Instances

The @Newify transformation annotation allows other ways to create a new instance of a class. We can use a new() method on the class or even omit the whole new keyword. The syntax is copied from other languages like Ruby and Python. If we use the @Newify annotation we get a slightly more readable piece of code (in some situations). We can use parameters in the annotation to denote all those classes we want to be instantiated with the new() method or without the new keyword.

class Author {
    String name
    List books
class Book { 
    String title 

def createKing() {
    new Author(name: 'Stephen King', books: [
        new Book(title: 'Carrie'),
        new Book(title: 'The Shining'),
        new Book(title: 'It')

assert 3 == createKing().books.size()
assert 'Stephen King' == createKing().name
assert 'Carrie' == createKing().books.getAt(0).title

def createKingRuby() { 'Stephen King', books: [ 'Carrie'), 'The Shining'), 'It')

assert 3 == createKingRuby().books.size()
assert 'Stephen King' == createKingRuby().name
assert 'Carrie, The Shining, It' == createKingRuby().books.title.join(', ')

@Newify([Author, Book]) 
def createKingPython() {
    Author(name: 'Stephen King', books: [
        Book(title: 'Carrie'),
        Book(title: 'The Shining'),
        Book(title: 'It')

assert 3 == createKingPython().books.size()
assert 'Stephen King' == createKingPython().name
assert 'It' == createKingPython().books.title.find { it == 'It' }