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

前端 未结 8 936
我寻月下人不归
我寻月下人不归 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:36

    I think you are talking about class level variables. As mentioned above using global variable/class level variables are not a good practice.

    If you really want to use it. and if you are sure that there will not be impact...

    Declare any variable out side the method. at the class level with out the variable type

    eg:

    {
       method()
       {
          a=10
          print(a)
       }
    
    // def a or int a wont work
    
    a=0
    
    }
    
    0 讨论(0)
  • 2020-11-28 22:37
    def sum = 0
    
    // This method stores a value in a global variable.
    def add =
    { 
        input1 , input2 ->
        sum = input1 + input2;
    }
    
    // This method uses stored value.
    def multiplySum =   
    {
        input1 ->
            return sum*input1;
    }
    
    add(1,2);
    multiplySum(10);
    
    0 讨论(0)
  • 2020-11-28 22:38
    class Globals {
       static String ouch = "I'm global.."
    }
    
    println Globals.ouch
    
    0 讨论(0)
  • 2020-11-28 22:40

    Just declare the variable at class or script scope, then access it from inside your methods or closures. Without an example, it's hard to be more specific for your particular problem though.

    However, global variables are generally considered bad form.

    Why not return the variable from one function, then pass it into the next?

    0 讨论(0)
  • 2020-11-28 22:44

    Like all OO languages, Groovy has no concept of "global" by itself (unlike, say, BASIC, Python or Perl).

    If you have several methods that need to share the same variable, use a field:

    class Foo {
        def a;
    
        def foo() {
            a = 1;
        }
        def bar() {
            print a;
        }
    }
    
    0 讨论(0)
  • 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.
    }
    
    0 讨论(0)
提交回复
热议问题