In Scala, final declares that a member may not be overridden in subclasses. For example:
class Parent {
val a = 1
final val b = 2
}
class Subclass extends Parent {
override val a = 3 // this line will compile
override val b = 4 // this line will not compile
}
Also, as discussed in Why are `private val` and `private final val` different?, if a final val field is holding a "constant value", a constant primitive type, access to it will be replaced with the bytecode to load that value directly.
You also cannot use non-
final
val
s in (Java) annotations.For example, this:
will only compile if
MOD_ID
is declared asfinal
.In Scala,
final
declares that a member may not be overridden in subclasses. For example:Also, as discussed in Why are `private val` and `private final val` different?, if a
final val
field is holding a "constant value", a constant primitive type, access to it will be replaced with the bytecode to load that value directly.final
members cannot be overridden, say, in a sub-class or trait.Legal:
Illegal:
You'll get an error such as this: