Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of declaring an object as "final"?

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 
like image 512
fredoverflow Avatar asked Sep 27 '14 21:09

fredoverflow


People also ask

What happens if we declare an object as final?

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.

Why do we declare a class as final?

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.

What happens when we declare object as final in Java?

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.

What is the point of final variables?

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.


1 Answers

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.)

like image 60
som-snytt Avatar answered Sep 19 '22 03:09

som-snytt