35

What is the reason for vals 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?

0__
  • 66,707
  • 21
  • 171
  • 266
  • Hm. what about traits that might be used? – Tony K. Sep 06 '12 at 22:28
  • @TonyK. - what do you mean? Even if I had `trait T { def a: Int }`, the object would override `a` in the linearisation rules. If I had `trait T { def a: Int = 33 }`, ok in that case `override final val` is not possible. But I think that still doesn't disqualify the approach of making _non-overriding_ vals final by default. – 0__ Sep 06 '12 at 23:27
  • Agreed. I am relatively new to Scala...was trying to explore possible avenues you had not thought of. – Tony K. Sep 07 '12 at 00:10
  • 1
    You should change the accepted answer to @extempore's (Paul Phillips). In this case, `final` causes the value to be inlined during compilation. – drstevens Jan 24 '14 at 20:46

3 Answers3

27

This is addressed explicitly in the specification, and they are automatically final:

Members of final classes or objects are implicitly also final, so the final modifier is generally redundant for them, too. Note, however, that constant value definitions (§4.1) do require an explicit final modifier, even if they are defined in a final class or object.

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:

object NonFinal {
  val a = 0
}

object Final {
  final val a = 0
}

javap does show a difference:

public final class NonFinal$ implements scala.ScalaObject {
  public static final NonFinal$ MODULE$;
  public static {};
  public int a();
}

public final class Final$ implements scala.ScalaObject {
  public static final Final$ MODULE$;
  public static {};
  public final int a();
}

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.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
  • 2
    I thought you could only switch on constant values, in which case 2.10-M7 has removed the requirement for `final` that you quoted. No? – Rex Kerr Sep 06 '12 at 22:41
  • @RexKerr: Indeed. I don't remember seeing that in any of the change logs, but I'll check again. – Travis Brown Sep 06 '12 at 22:48
  • 1
    Thanks, that spec quote is quite clear, saying `val`s do need explicit `final`. The 2.10.0-M7 is strange then, might be worth checking the resulting pattern match code (perhaps it `@switch` is silently dropped?) – 0__ Sep 06 '12 at 23:31
  • @0__: You read it as requiring the modifier? I'm just confused by it, now, but would have interpreted it as saying at the very least that if there's no chance of a constant value definition (e.g., we've got `"0".toInt` or `new A` on the right-hand side) then the `final` is redundant. – Travis Brown Sep 06 '12 at 23:38
  • 1
    Yes I read it that way, although I _do disagree_ with the spec here. As I said, I think it's unnecessary noise. – 0__ Sep 06 '12 at 23:44
  • That the javap listing shows a difference may not matter. My recollection from Java is that a final class implies finality of all its fields and methods too. Therefore, as far as the compiler wanting to make optimisations is concerned, it has the same information so it should be able to make the same optimisations. Whether it does so or not would be a matter of how well that bit of the compiler has been implemented. – Rick-777 Sep 08 '12 at 22:25
  • Add a case to see the warning in 2.10+. Now doc says: Note: for pattern matches with one or two cases, the compiler generates jump instructions. Annotating such a match with @switch does not issue any warning. – som-snytt Jul 03 '17 at 04:48
23

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.

object A { final val x = 55 }
object B { def f = A.x }

When you compile this, B.f returns 55, literally:

public int f();
  0: bipush        55
  2: ireturn       

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:

  0: getstatic     #19                 // Field A$.MODULE$:LA$;
  3: invokevirtual #22                 // Method A$.x:()I
  6: ireturn       

Also, to correct one of the other answers, final does not mean immutable in scala.

psp
  • 12,138
  • 1
  • 41
  • 51
3

To address the central question about final on an object, I think this clause from the spec is more relevant:

A constant value definition is of the form final val x = e where e is a constant expression (§6.24). The final modifier must be present and no type annotation may be given. References to the constant value x are themselves treated as constant expressions; in the generated code they are replaced by the definition’s right-hand side e.

Of significance:

  • No type annotation may be given
  • The expression e is used in the generated code (by my reading, as the original unevaluated constant expression)

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.

Tony K.
  • 5,535
  • 23
  • 27