gMale
gMale

Reputation: 17895

Groovy: How to set a property/field/def from a method in a groovy script?

Question

Given a simple groovy script (not a class!), how do you set the value of a property/field that is outside a method?

Example

The following code does not work as expected:

def hi;

def setMyVariable() {
    hi = "hello world!"
}

setMyVariable()
assert hi == "hello world!"    //fails
println hi                     //prints null

Failed Attempts

I have tried many things, including the following, which have all failed

...

def setMyVariable() {
    this.hi = "hello world!"
}

...

public void setMyVariable() {
    hi = "hello world!"
}

...

public String hi;
public void setMyVariable() {
    this.hi = "hello world!";
}

Summary

What is the simplest way to set a variable that is external to a method declaration? The only thing I can get to work is the following. There must be an easier way!

def hi;

def setMyVariable() {
    this.binding.setVariable("hi", "hello world!")
}

setMyVariable()

println this.binding.getVariable("hi")
assert this.binding.getVariable("hi") == "hello world!"  //passes
assert hi == "hello world!"  //fails

Upvotes: 3

Views: 6880

Answers (3)

epidemian
epidemian

Reputation: 19219

You may assign an anonymous function to a variable instead of defining a method:

def hi

def setMyVariable = {
    hi = "hello world!"
}

setMyVariable()
assert hi == 'hello world!'

Upvotes: 4

denis.solonenko
denis.solonenko

Reputation: 11775

In Groovy 1.8.x you can do this:

@groovy.transform.Field def hi

Variable annotation used for changing the scope of a variable within a script from being within the run method of the script to being at the class level for the script.

Upvotes: 4

talnicolas
talnicolas

Reputation: 14053

Take a look at that page of Groovy doc:

When you define a variable in a script it is always local. But methods are not part of that scope. So defining a method using different variables as if they were attributes and then defining these variables normally in the script leads to problems.

In this case you have to make hi part of the binding (easier way would be not to use the def actually, so it's gonna be automatically part of the binding).

Upvotes: 1

Related Questions