I am trying to discover if a trait's value has an annotation associated to it. After reviewing the Scala 2.10-M7 reflection API I thought that the getAnnotations method (located in Symbol) could be a great candidate, but it is returning an empty list, as shown in the following REPL session:
scala> class W extends scala.annotation.Annotation
defined class W
scala> trait A { @W val a: Int }
defined trait A
scala> typeOf[A].members.last
res0: $r.intp.global.Symbol = value a
scala> res0.getAnnotations
res1: List[$r.intp.global.AnnotationInfo] = List()
Are those "annotations" the same annotations I am trying to deal with? How can I know if a is annotated with W?
Scala reflection enables a form of metaprogramming which makes it possible for programs to modify themselves at compile time. This compile-time reflection is realized in the form of macros, which provide the ability to execute methods that manipulate abstract syntax trees at compile-time.
Annotations are a kind of comment or meta data you can insert in your Java code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection. Here is an example of class annotation: @MyAnnotation(name="someName", value = "Hello World") public class TheClass { }
Scala Annotations are metadata added to the program source code. Annotations are allowed on any kind of definition or declaration including vals, vars, classes, objects, traits, defs and types. Annotations are used to associate meta-information with definitions.
We use the reflection API to get class and method information from where we can read information about annotation attached to the class or the method.
Looks like a bug: https://issues.scala-lang.org/browse/SI-6325
update. Actually it's not a bug, but a combination of non-obvious ways of how annotations work in Scala. There is a way to make abstract annotated vals in traits work as desired. Take a look at the discussion at the aforementioned links for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With