2017-05-11 3 views
1

ich diesen Fehler:Warum groovy findet nicht meinen Variable in ihrem Umfang

Apparent variable 'b' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes: 
You attempted to reference a variable in the binding or an instance variable from a static context. 
You misspelled a classname or statically imported field. Please check the spelling. 
You attempted to use a method 'b' but left out brackets in a place not allowed by the grammar. 
@ line 11, column 12. 
     int a = (b + 5); 
      ^

Warum ist es nicht b als Variable zu erkennen? Ich versuche zu testen, wie Scoping in Groovy funktioniert. Ist es statisch oder dynamisch?

class practice{ 
     static void main(String[] args) 
     {  int b=5; 
       foo(); // returns 10 
       bar(); // returns 10 
       println('Hello World'); 
     } 
     //public int b = 5; 
     static void foo() 
     { 
       int a = (b + 5); 
       println(a); 
     } 

     static void bar() 
     { 
       int b = 2; 
       println(foo()); 
     } 
} 

Antwort

1

Es gibt zwei lokale Variablen namens b, eine in main und eine in bar. Die foo-Methode kann keine von beiden sehen. Wenn groovy dynamisches Scoping verwendet, würde es den Wert von b in bar sehen und es in foo verwenden, was nicht geschieht, zeigt an, dass das Scoping statisch ist.

Es sieht so aus, als käme der Code von here. Hier ist, wie ich es Groovy übersetzen würde:

public class ScopeExample { 
    int b = 5 
    int foo() { 
     int a = b + 5 
     a 
    } 
    int bar() { 
     int b = 2 
     foo() 
    } 
    static void main(String ... args) { 
     def x = new ScopeExample() 
     println x.foo() 
     println x.bar() 
    } 
} 

Laufhaupt druckt

10 
10 

zeigt, dass die lokale Variable vor dem Aufruf das Ergebnis nicht ändern.

Scoping in groovy ist lexikalisch (dh statisch), nicht dynamisch. Groovy, Java, Scheme, Python und JavaScript (unter vielen anderen) sind alle lexikalisch begrenzt. Beim lexikalischen Scoping entscheidet der Kontext, in dem der Code definiert ist, was im Umfang ist, nicht der Kontext zur Laufzeit bei der Ausführung. Um herauszufinden, was mit dynamischem Scoping verbunden ist, muss der Aufrufbaum bekannt sein.