How do I create and access the global variables in Groovy?

前端 未结 8 978
我寻月下人不归
我寻月下人不归 2020-11-28 22:29

I need to store a value in a variable in one method and then I need to use that value from that variable in another method or closure. How can I share this value?

8条回答
  •  天涯浪人
    2020-11-28 22:53

    In a Groovy script the scoping can be different than expected. That is because a Groovy script in itself is a class with a method that will run the code, but that is all done runtime. We can define a variable to be scoped to the script by either omitting the type definition or in Groovy 1.8 we can add the @Field annotation.

    import groovy.transform.Field
    
    var1 = 'var1'
    @Field String var2 = 'var2'
    def var3 = 'var3'
    
    void printVars() {
        println var1
        println var2
        println var3 // This won't work, because not in script scope.
    }
    

提交回复
热议问题