2014年3月15日 星期六

[ Groovy Doc ] Scoping and the Semantics of "def"

來源自 這裡 
Preface: 
Java has two basic informal rules for scoping: 
Principle #1: "A variable is only visible in the block it is defined in and in nested blocks".
Principle #2: "A variable can't be visible more than one time".

Java does know classwide variables and local variablesLocal variables are defined as method parameter or inside the method block. Classwide variables are defined as attributes of the class. Of course Java does violate this first principle I showed at top here a little since I can access class wide variables from outside the class, if the access modifier is for example public. A local variable of the same name as an attribute does not violate the second principle, as the attribute is hidden by the local variable and with this no longer visible without using a qualifier like "this". 

Now, what about Groovy? 
In Groovy we also have these two principles, but since we have different constructs, we may lay out these principles in a different way. Let us start with local variables. 
* In Groovy you are neither allowed to define two local variables of the same name, just like in Java.
* You are allowed to hide an attribute by defining a local variable of the same name, just like in Java.

So what is different? When you define a variable in a script it is always local. But methods are not part of that scope. So defining a method using different variables as if they were attributes and then defining these variables normally in the script leads to problems. Example: 
- Example of disallowed definition in scripts 
  1. String attribute = "bar"  
  2. void aMethod(){  
  3.   assert attribute == "bar" // Not allowed !  
  4. }  
  5. aMethod()  
Executing this code you get an exception talking about a missing property or field. 

The only things the method has access to are: 
* the binding,
* attributes defined by the base class, and
* the dynamic properties defined by the MetaClass (explanations for these will follow in Dynamic Groovy).

When is something in the Binding and when not? 
That's easy. When it is not defined, it is in the binding. The trick is - and that is admittedly not easy for Java programers - to not to define the variable before using it, and it will go into the binding. Any defined variable is local. Please note: the binding exists only for scripts
- Example of binding variable in scripts 
  1. attribute = "bar" //Binding variable  
  2. void aMethod(){  
  3.   assert attribute == "bar" // Not allowed !  
  4. }  
  5. aMethod()  

What is this "def" I heard of? 
"def" is a replacement for a type name. In variable definitions it is used to indicate that you don't care about the type. In variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is needed to the make variable definitions detectable for the Groovy parser. You can think of "def" as an alias of "Object" and you will understand it in an instant. 

These definitions may occur for local variables in a script or for local variables and properties/fields in a class. "def" can also replace "void" as the return type in a method definiton. Below example show how "def" can be assigned to different class Object: 
  1. def dynamic  =  1  
  2. dynamic = "I am a String stored in a variable of dynamic type"  
  3. int typed = 2  
  4. typed = "I am a String stored in a variable of type int??"    // throws ClassCastException  
The assignment of a string, to a variable of type int will fail. A variable typed with "def" allows this. 

A Closure is a block: 
In the terms of the principles above a closure is a block. A variable defined in a block is visible in that block and all blocks that are defined in that block. For example in Java: 
- a java code 
  1. {  
  2.   int i=1;  
  3.   {  
  4.     System.out.println (i);  
  5.   }  
  6. }  
Such a block may be defined freely as in the example above, or by loops, synchronized statements, try-catch, switch, ... all that has "{". 

In Groovy we have an additonal structure with "{", the closure. To follow the principles above, it is not allowed to define two variables of the same name in a closure. 
- Not allowed 
  1. def closure = { int i; int i }  
And of course, the same for combinations with nested closures. 
- Invalid double definition of variables 
  1. def outer = {  
  2.   int i  
  3.   def inner = { int i }  
  4. }  
A block ends with its corresponding "}". So it is allowed to reuse that name later in a different block. 
- Allowed 
  1. def closure1 = { parameter ->  
  2.   println parameter  
  3. }  
  4. def closure2 = { parameter ->  
  5.   println parameter  
  6. }  
Both closures define a local varibale named "parameter", but since these closures are not nested, this is allowed. Note: unlike early versions of Groovy and unlike PHP, a variable is visible in the block, not outside. Just like in Java. 

And "it"? 
"it" is a special variable name, that is defined automatically inside a closure. It refers always to the first parameter of the closure, or null, if the closure doesn't have any parameters. When using nested cosures (closures in closures) the meaning of "it" depends on the closure you are in. 
- implicit it in closures 
  1. def c = { it }  
  2. assert c()  == null  
  3. assert c(1) == 1  
  4. def outer = {  
  5.   def inner = { it+1 }  
  6.   inner(it+1)  
  7. }  
  8. assert outer(1) == 3  
The keyword "static" 
"static" is a modifier for attributes (and methods, but this is not at issue here). It defines the "static scope". That means all variables not defined with "static" are not part of that static scope and as such not visible there. There is no special magic to this in Groovy. So for an explanation of "static" use any Java book.

沒有留言:

張貼留言

[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...