- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Why cannot vals be the value of annotations?
Sat, 2011-03-26, 23:06
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
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