9

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?

Eugene Burmako
  • 13,028
  • 1
  • 46
  • 59
neutropolis
  • 1,884
  • 15
  • 34

1 Answers1

6

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.

Eugene Burmako
  • 13,028
  • 1
  • 46
  • 59
  • I thought Scala annotations were not preserved at run time? – Daniel C. Sobral Sep 08 '12 at 00:50
  • 1
    They aren't supposed to be visible by Java reflection, but they should be stored in Scala pickles. What I overlooked though is that you need to subclass either `StaticAnnotation` or `ClassfileAnnotation` for that to work. Subclassing just `Annotation` won't cut it, at least according to Scaladoc. – Eugene Burmako Sep 08 '12 at 04:45
  • In a few days, when I have time, I'll clarify the intended behavior, apply fixes if necessary and will update the answer accordingly. – Eugene Burmako Sep 08 '12 at 04:46
  • 1
    The bug still stands, because even if W extends StaticAnnotation, getAnnotations returns Nil. Changing a to def instead of val fixes the problem. – Eugene Burmako Sep 08 '12 at 04:51