Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么groovy在其作用域中找不到我的变量_Groovy_Scope_Static - Fatal编程技术网

为什么groovy在其作用域中找不到我的变量

为什么groovy在其作用域中找不到我的变量,groovy,scope,static,Groovy,Scope,Static,我得到这个错误: 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 misspell

我得到这个错误:

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

有两个局部变量称为b,一个在main中,一个在bar中。foo方法无法看到它们中的任何一个。如果groovy使用动态作用域,那么它将在bar中看到b的值,并在foo中使用它,如果不这样做,则表明作用域是静态的

看起来发布的代码来自。下面是我如何将其转换为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(以及许多其他语言)都是词汇范围的。通过词法作用域,定义代码的上下文决定作用域中的内容,而不是执行时的运行时上下文。弄清楚什么与动态作用域有关需要了解调用树