This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Why cannot vals be the value of annotations?

1 reply
reto 2
Joined: 2011-03-26,
User offline. Last seen 42 years 45 weeks ago.

The following would seem to be useful code to me

class SomeOuterClass {

val path = "admin/renderlets/overview"
@Path(path)
object RenderletsOverview {
...

Unfortunately the above doesn't compile and I get:
error: annotation argument needs to be a constant; found: path
@Path(path)

As a val is constant I don't see the rationale for this limitation,
duplicating strings needed elsewhere in annotations seem awkward.

Cheers,
Reto

Jason Zaugg
Joined: 2009-05-18,
User offline. Last seen 38 weeks 5 days ago.
Re: Why cannot vals be the value of annotations?

On Sat, Mar 26, 2011 at 11:06 PM, reto wrote:
> The following would seem to be useful code to me
>
> class SomeOuterClass {
>
>  val path = "admin/renderlets/overview"
>  @Path(path)
>  object RenderletsOverview {
> ...
>
> Unfortunately the above doesn't compile and I get:
> error: annotation argument needs to be a constant; found: path
> @Path(path)
>
> As a val is constant I don't see the rationale for this limitation,
> duplicating strings needed elsewhere in annotations seem awkward.

That val is a member of a class, that can't be accessed without an
instance of the class, and could even be overriden by a subclass. That
isn't suitable for an annotation argument, which must be known at
compile time.

You need to reference a constant expression, such as:

object O {
final val constantExpr = ""
}

@(O.constantExpr) class Foo

One subtle point: 'final' is required, and a type annotation must be
omitted. For all the details, refer to 6.24 and 4.1 of the Scala
Reference.

-jason

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland