« Return to Thread: What happens to 'def' attributes in scripts?

Re: What happens to 'def' attributes in scripts?

by Edward Sumerfield-2 :: Rate this Message:

Reply to Author | View in Thread

Woo, I can answer this one.

When groovyc compiles this script it has to convert into java byte code. So, the n=1 become Test instance attributes, the def n=1 become main method local variables.

The case without def results in java looking something like this:

    class Test
    {
        Object n = 1
        Object m = 2

        public static void main(String args[])
        {
            add(m)
        }

        void add(Object another)
        {
            another += n
        }
    }

this works because there are no defs and the scoping of n and m remain accessible by the add method

However, add the def and they become local variables in the main method and now are not accessible by add.

    class Test
    {
        public static void main(String args[])
        {
            Object n = 1
            Object m = 2

            add(m)
        }

        void add(Object another)
        {
            another += n
        }
    }



On Tue, Jun 30, 2009 at 4:21 PM, Niels B Nielsen <niels.b.nielsen@...> wrote:

Hi,

When I have my users define their own script, they produce something similar to this:

Test.groovy

--------------

n=1

m=2

 

def add(another) {

  int x = n+another

  println "x is ${x}"

}

add(m)

-------------------------

The def method is added to Test.class, and the variables are added to the Binding. That much I have verified, but when the users sometimes write

 

def n=1

def m=2

 

The script fails to recognize n in the add method. (no such property: n for class: Test)

 

Clearly, neither n nor m is a field of class Test, nor are they present in the binding. However, m is still accessible to be an argument to the add method.

 

I can easily tell the user not to specify def in front of variables, only in front of methods, but I cannot fully explain why.

 

Where is the variable stored? In the main method? or just inline replaced during parsing? Hope you can help me with an answer.

 

Regards,

/Niels


This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.


 « Return to Thread: What happens to 'def' attributes in scripts?