Search code examples
groovy

What is script class in Groovy?


I'm learning groovy and could not comprehend this statement for the below piece of code.

Checked other related documentation but no luck. Can someone please help here ? Thanks.

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.

Code snippet:

import groovy.transform.Field
@Field List awe = [1, 2, 3]
def awesum() { awe.sum() }
assert awesum() == 6

Solution

  • during compilation groovy transforms the script into a java class that extends groovy.lang.Script

    so, the code in question will be transformed to approximately this:

    public class scriptXYZ extends groovy.lang.Script { 
        java.util.List awe 
        
        public scriptXYZ() {
            awe = [1, 2, 3]
        }
    
        public java.lang.Object run() {
            assert this.awesum() == 6
        }
    
        public java.lang.Object awesum() {
            return awe.sum()
        }
    }
    

    without @Field annotation the variable awe will be a part of run() method and obviously awesum() function will throw an error :

    public class scriptXYZ extends groovy.lang.Script { 
        public scriptXYZ() {
        }
    
        public java.lang.Object run() {
            List awe = [1, 2, 3]
            assert this.awesum() == 6
        }
    
        public java.lang.Object awesum() {
            return awe.sum()
        }
    }
    
    

    in groovyconsole you can select menu Script -> Inspect AST to see a class generated for your script

    enter image description here