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

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

提交回复
热议问题