is there a way to specify a constructor for a groovy script?

Solution 1:

You may use setter method

(Foo.groovy):

import groovy.transform.Field

@Field def bar

void setBar(def bar){
    this.bar = "${bar}!"
    println "Setter is executed. ${bar} -> ${this.bar}"
}

And if the calling party will look like

import Foo
def foo = new Foo(bar: 'baz')
println foo.bar

the following result appears:

Setter is executed. baz -> baz!
baz!

Solution 2:

You can have a method like initialise that acts as a constructor. That way you can use it for multiple arguments as well.

import groovy.transform.Field

@Field def bar

// initialise can be used in-place of constructor for enclosing class
def initialise(args) {
  bar = "${args.bar}!"
  this // return initialised object
}

def someMethod() {
  println(bar)
}

This can be called as follows

def foo = new Foo().initialise(args)

foo.someMethod()