What is the reason for val
s not (?) being automatically final in singleton objects? E.g.
object NonFinal {
val a = 0
val b = 1
def test(i: Int) = (i: @annotation.switch) match {
case `a` => true
case `b` => false
}
}
results in:
<console>:12: error: could not emit switch for @switch annotated match
def test(i: Int) = (i: @annotation.switch) match {
^
Whereas
object Final {
final val a = 0
final val b = 1
def test(i: Int) = (i: @annotation.switch) match {
case `a` => true
case `b` => false
}
}
Compiles without warnings, so presumably generates the faster pattern matching table.
Having to add final
seems pure annoying noise to me. Isn't an object
final per se, and thus also its members?
To address the central question about final on an object, I think this clause from the spec is more relevant:
Of significance:
It sounds to me like the compiler is required by the spec to use these more like macro replacements rather than values that are evaluated in place at compile time, which could have impacts on how the resulting code runs.
I think it is particularly interesting that no type annotation may be given.
This, I think points to our ultimate answer, though I cannot come up with an example that shows the runtime difference for these requirements. In fact, in my 2.9.2 interpreter, I don't even get the enforcement of the first rule.
This is addressed explicitly in the specification, and they are automatically final:
Your
final
-less example compiles without errors (or warnings) with 2.10-M7, so I'd assume that there's a problem with the@switch
checking in earlier versions, and that the members are in fact final.Update: Actually this is more curious than I expected—if we compile the following with either 2.9.2 or 2.10-M7:
javap
does show a difference:You see the same thing even if the right-hand side of the value definitions isn't a constant expression.
So I'll leave my answer, but it's not conclusive.
You're not asking "why aren't they final", you're asking "why aren't they inlined." It just happens that final is how you cue the compiler that you want them inlined.
The reason they are not automatically inlined is separate compilation.
When you compile this, B.f returns 55, literally:
That means if you recompile A, B will be oblivious to the change. If x is not marked final in A, B.f looks like this instead:
Also, to correct one of the other answers, final does not mean immutable in scala.