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

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

    Could not figure out what you want, but you need something like this ? :

    ​def a = { b -> b = 1 }
    ​bValue = a()
    println b // prints 1
    

    Now bValue contains the value of b which is a variable in the closure a. Now you can do anything with bValue Let me know if i have misunderstood your question

    0 讨论(0)
  • 2020-11-28 22:56
    def iamnotglobal=100 // This will not be accessible inside the function
    
    iamglobal=200 // this is global and will be even available inside the 
    
    def func()
    {
        log.info "My value is 200. Here you see " + iamglobal
        iamglobal=400
        //log.info "if you uncomment me you will get error. Since iamnotglobal cant be printed here " + iamnotglobal
    }
    def func2()
    {
       log.info "My value was changed inside func to 400 . Here it is = " + iamglobal
    }
    func()
    func2()
    

    here iamglobal variable is a global variable used by func and then again available to func2

    if you declare variable with def it will be local, if you don't use def its global

    0 讨论(0)
提交回复
热议问题