46

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
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
fredoverflow
  • 256,549
  • 94
  • 388
  • 662

2 Answers2

38

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

som-snytt
  • 39,429
  • 2
  • 47
  • 129
  • This is totally right. It took me a while to persuade myself of that, though. For a bit more verbose, painful detail, see the updates in [this duplicate question](http://stackoverflow.com/questions/30265070/whats-the-point-of-nonfinal-singleton-objects-in-scala). See also [this question](http://stackoverflow.com/questions/17308141/what-are-the-subtle-differences-between-val-and-singleton-objects) – Steve Waldman May 15 '15 at 18:11
  • 6
    `-Yoverride-objects` never worked well and has been removed entirely from Scala 2.13. – Seth Tisue Sep 14 '18 at 23:04
  • 2
    @SethTisue basically you are paid to spoil our fun! If only this site had tags for "opinionated Scala" vs "anything goes Scala". – som-snytt Sep 15 '18 at 00:34
31

It makes no difference; object definitions are always final. The language specification explicitly mentions this in 5.4 Modifiers:

final is redundant for object definitions.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
  • 1
    there is a recent proposal to actually forbid it: https://github.com/scala/bug/issues/11094 – Seth Tisue Sep 14 '18 at 23:06
  • 1
    It does make a difference in the generated bytecode though. Depending on the scala version, the bytecode may or may not contain the `final` flag (2.11 adds it, 2.12 does not) – Nicolas Rinaudo Jan 04 '19 at 13:49