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

Type dependent annotations?

No replies
Sebastien Bocq
Joined: 2008-12-18,
User offline. Last seen 42 years 45 weeks ago.
Hello,

Today you have the following possibilities to specify the element to which an annotation is applicable:
  • @Target(ElementType.TYPE)—can be applied to any element of a class
  • @Target(ElementType.FIELD)—can be applied to a field or property
  • @Target(ElementType.METHOD)—can be applied to a method level annotation
  • @Target(ElementType.PARAMETER)—can be applied to the parameters of a method
  • @Target(ElementType.CONSTRUCTOR)—can be applied to constructors
  • @Target(ElementType.LOCAL_VARIABLE)—can be applied to local variables
  • @Target(ElementType.ANNOTATION_TYPE)—indicates that the declared type itself is an annotation type
Wouldn't it be useful to have an extra possibility and restrict the target to elements of a certain type T? For example:
  • @Target(T.Field)—can be applied to a field of type T
Couple that to an attribute that specifies if the annotation is required or not on all elements of type T and the compiler can check if an annotation is missing or applied to an element of the wrong type.

I sketched how it could look like in the example below:
@Retention(RetentionPolicy.RUNTIME)
@Target(T.FIELD, required = true)
public @interface TAnnotation {
public String a();
public String b();
}

class X {
@TAnnotation(a="Hello", b="World") // ok
val f = new T

@TAnnotation(a="Hello", b="World") // error: annotation only valid for fileds of type T, found U
val g = new U

// error: TAnnotation annotation missing
val h = new T
}

Is there a way to support this without breaking everything?

Thanks,
Sebastien

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