2017年1月18日 星期三

[ 常見問題 ] How do I create and access the global variables in Groovy?

Source From Here
Question
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?

How-To
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.
  1. import groovy.transform.Field  
  2.   
  3. var1 = 'var1'  
  4. @Field String var2 = 'var2'  
  5. def var3 = 'var3'  
  6.   
  7. void printVars() {  
  8.     println var1  
  9.     println var2  
  10.     println var3 // This won't work, because not in script scope.  
  11. }  

This message was edited 3 times. Last update was at 18/01/2017 16:53:45

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...