【问题标题】:def vs final def in GroovyGroovy 中的 def 与最终 def
【发布时间】:2018-06-01 14:36:32
【问题描述】:

我在Groovy 中使用Spock framework 编写了简单的测试

class SimpleSpec extends Specification {

    def "should add two numbers"() {
        given:
            final def a = 3
            final b = 4
        when:
            def c = a + b
        then:
            c == 7
    }
}

变量a 是使用deffinal 关键字组合声明的。变量 b 仅使用 final 关键字声明。

我的问题是:这两个声明之间有什么区别(如果有的话)?应该将一种方法优先于另一种方法吗?如果有,为什么?

【问题讨论】:

    标签: groovy spock


    【解决方案1】:

    在方法中声明的final变量在groovy中被当作普通变量处理

    检查下面的类和由 groovy (2.4.11) 生成的类

    ps:spock 中的given: 部分可能生成不同的代码...

    【讨论】:

    • 那么,有没有区别?
    • 我认为您的屏幕截图没有任何相关性,可能您发布了错误的截图。我认为您想向我们展示 AST 树的字节码视图或子节点。也许你想解决这个问题。
    • 我想表明,在解析、转换和规范化步骤之后,两个变量声明是相同的,所以后面的步骤不会改变这个声明,并且在字节码中你不会看到差异。如果我错了,请发布您的正确答案。
    • 我从来没有说过你错了!我什至在我的回答中提到了你,在测试中说明了同样的事情。我只是以为你想分享另一个屏幕截图。你分享的那个解释对我不是很有启发,现在我才看到。很容易忽略 AST 浏览器源代码视图中只有 java.lang.Object a = 111 而没有 final。比“检查下图”或相关部分周围的红框多一点解释性的散文会有所帮助。
    【解决方案2】:

    用户 daggett 没错,final 在 Groovy 中不会将局部变量设为 final。关键字只对类成员有影响。这是一个小例子:

    package de.scrum_master.stackoverflow
    
    import spock.lang.Specification
    
    class MyTest extends Specification {
      def "Final local variables can be changed"() {
        when:
        final def a = 3
        final b = 4
        final int c = 5
        then:
        a + b + c == 12
    
        when:
        a = b = c = 11
        then:
        a + b + c == 33
      }
    
      final def d = 3
      static final e = 4
      final int f = 5
    
      def "Class or instance members really are final"() {
        expect:
        d + e + f == 12
    
        when:
        // Compile errors:
        // cannot modify final field 'f' outside of constructor.
        // cannot modify static final field 'e' outside of static initialization block.
        // cannot modify final field 'd' outside of constructor.
        d = e = f = 11
        then:
        d + e + g == 33
      }
    }
    

    更新:我使用 Groovy 2.5 将我的一个 Spock 项目切换到 1.3 版,并注意到由于编译器检测到对最终局部变量的重新分配,该测试现在不再编译。 IE。 Groovy

    【讨论】:

    • 请参阅我关于 Groovy 2.5 中行为变化的更新。
    猜你喜欢
    • 1970-01-01
    • 2010-09-16
    • 2020-03-04
    • 1970-01-01
    • 2012-11-02
    • 2017-04-11
    • 2010-11-05
    • 2010-09-16
    相关资源
    最近更新 更多