I just noticed that it's possible to declare objects as final
in Scala:
final object O
What's the point of doing that? One cannot inherit from objects anyway:
object A object B extends A // not found: type A
If we use the final keyword with an object, it means that the reference cannot be changed, but its state (instance variables) can be changed. Making an object reference variable final is a little different from a final variable. In that case object fields can be changed but the reference can't be changed.
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class.
final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Whereas immutable means that the object's actual value can't be changed, but you can change its reference to another one.
The term effectively final variable was introduced in Java 8. A variable is effectively final if it isn't explicitly declared final but its value is never changed after initialization. The main purpose of effectively final variables is to enable lambdas to use local variables that are not explicitly declared final.
Not that anyone does this, but:
$ scala -Yoverride-objects Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11). Type in expressions to have them evaluated. Type :help for more information. scala> trait A { object O } ; trait B extends A { override object O } defined trait A defined trait B scala> trait A { final object O } ; trait B extends A { override object O } <console>:8: error: overriding object O in trait A; object O cannot override final member trait A { final object O } ; trait B extends A { override object O } ^
Possibly sometimes people want to do it. (For instance.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With