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
关键字声明。
我的问题是:这两个声明之间有什么区别(如果有的话)?是否应该将一种方法加到另一方面?如果是这样,为什么?
答案 0 :(得分:1)
答案 1 :(得分:1)
用户 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
}
}