Reputation: 2061
I have a groovy script called Foo.groovy
, an instance of that script can be constructed using the following syntax:
def foo = new Foo()
i know if Foo.groovy
looks like:
import groovy.transform.Field
@Field def bar
def someMethod() {
//...
}
the following syntax:
def foo = new Foo(bar: 'baz')
will use some default constructor and actually set the bar
field to baz
,
but let's say that i wanted to manipulate the passed value of bar
to add an
exclamation point at the end like so "${bar}!"
would like to be able to do something like the following (which doesn't work AFAIK):
import groovy.transform.Field
@Field def bar
Foo(args) {
bar = "${args.bar}!"
}
def someMethod() {
//...
}
Is there an idiomatic way to accomplish that in groovy?
Upvotes: 0
Views: 3341
Reputation: 61
Rather than have a named initializer, I used the call
method, ending in return this
:
def call(def env, String name) {
this.env = env
this.markDownName = "*${name}*"
return this
}
then I can have the following idiomatic use of the constructor, with two sets of parantheses:
def helper = new Helper()(env, "front end verification")
Upvotes: 0
Reputation: 700
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()
Upvotes: 1
Reputation: 1434
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!
Upvotes: 1
Reputation: 1179
Any free variable in the main body of the script can be satisfied out of the Binding object. It works pretty much like a map because it has a map-based constructor and has overloaded getProperty and setProperty. http://docs.groovy-lang.org/latest/html/gapi/groovy/lang/Binding.html
Main script:
def binding = new Binding(bar: 'baz')
def foo = new Foo(binding)
foo.run()
Foo.groovy:
someMethod(bar + '!')
def someMethod(baz) { // bar/baz value must be passed in
// do something with baz
}
I have not tried this out, but it should be easy enough to plug it into Groovy Console and see what happens.
Upvotes: 0