我已经使用 Spock framework 在 Groovy
中编写了简单的测试
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
使用 def
和 final
关键字组合声明。变量 b
仅使用 final
关键字声明。
我的问题是:这两个声明之间有什么区别(如果有)?是否应该优先考虑一种方法?如果是这样,为什么?
最佳答案
用户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 <= 2.4 中的不一致似乎已得到修复。
关于groovy - def 与 Groovy 中的最终 def,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50645835/