9

From the REPL:

scala> final val x = "x"
x: java.lang.String("x") = x

scala> @javax.persistence.Table(name = x) case class foo()
defined class foo

scala> final val x:java.lang.String = "x"
x: java.lang.String = x

scala> @javax.persistence.Table(name = x) case class foo()
<console>:6: error: annotation argument needs to be a constant; found: x
       @javax.persistence.Table(name = x) case class foo()

Can someone explain why this only works without a type?

2
  • Why do you use the keyword final ? Jul 28, 2011 at 20:38
  • final is necessary to create the literal constant that Daniel mentions below. Without it, you will get the same error mentioned above.
    – scalapeno
    Jul 28, 2011 at 22:29

1 Answer 1

8

Without the type, final val acts like a literal constant -- the identifier is replaced by its value at compile time. With the type, it becomes a reference to something stored somewhere, which cannot be used on annotations.

This is defined on section 4.1 of the specification:

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.

This is the only way you can get true named constants in Scala. They have performance benefits, they are really guaranteed not to mutate (even a final val with a type can be changed through reflection) and, of course, they can be used in annotations.

4
  • I guessed that was what was happening, but why does it work like that? Is there some benefit to doing it that way? Is there a case where this is a useful feature?
    – scalapeno
    Jul 28, 2011 at 22:28
  • @tritium6 I expanded my answer, but isn't use in annotations a useful enough case? Jul 28, 2011 at 22:35
  • Thanks for the expansion. You're right, the annotation case is useful. What I meant was, is there a useful case for the typed expression - why would you want to have a case where a final val is a reference?
    – scalapeno
    Jul 28, 2011 at 23:55
  • @tritium6 Consider the case of a library that defines constants. If it changes those constants and they are defined as literals, not references, then everything depending on the library (and using those constants) will need to be recompiled. Jul 29, 2011 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.