Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

scala - Why is a `val` inside an `object` not automatically final?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...