2017-05-11 41 views
1

我得到这个错误:为什么常规没有找到我的变量在其范围内

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); 
      ^

为什么没有承认B中的变量?我正在尝试测试Groovy中的范围工作方式。它是静态的还是动态的?

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()); 
     } 
} 

回答

1

有两个局部变量叫做b,一个在main中,一个在bar中。 foo方法看不到它们中的任何一个。如果groovy使用动态作用域,那么它会在bar中看到b的值,并在foo中使用它,这并没有发生,这表明范围是静态的。

它看起来像张贴的代码来自here。下面是我如何将其转换成Groovy:在

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() 
    } 
} 

运行主打印

10 
10 

显示,呼叫前局部变量不发生变化的结果。

groovy中的范围界定是词法(意思是静态的),而不是动态的。 Groovy,Java,Scheme,Python和JavaScript(其他很多)都是词汇范围的。使用词法范围界定代码的上下文决定了范围内的内容,而不是执行时的运行时上下文。找出与动态范围界定有什么联系需要知道调用树。

相关问题