Final local variables
You can use the final modifier on a local variable
to initialize the value and prevent the value from changing.
For example, the following code is valid:
class final1 {
function PrintGreeting() {
var f = "frozen"
f = "dynamic"
}
}
This code is not valid because it attempts to change the value of the final variable:
class final1 {
function PrintGreeting() {
final var f = "frozen"
f = "dynamic" // Compile error because it attempts to change a final variable
}
}
If you define a local variable as final, you can initialize
the value of the variable immediately in the declaration. Alternatively,
you can declare the variable as final
but not immediately initialize the variable with a value. You must set
the value in that function for all possible code paths. For example,
any if statements or other
flow control structures must set the value of the variable and not change
a value that previous code set. The Gosu compiler verifies that all code
paths initialize the final variable exactly once.
For example, the following code is valid:
function finalVar(a : boolean) {
final var b : int
if (a) {
b = 0
} else {
b = 1
}
}
If you remove the else
branch, the code is not valid because the final variable is initialized
only if a is true.
function finalVar(a : boolean) {
final var b : int // INVALID CODE, UNINITIALIZED IF "a" IS FALSE
if (a) {
b = 0
}
}
