Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Annotation Inheritance

In Scala, I have an annotation and a base trait with the annotation, but extending that class doesn't inherit the annotation:

scala> import scala.annotation.StaticAnnotation
import scala.annotation.StaticAnnotation

scala> case class AnnotationClass() extends StaticAnnotation
defined class AnnotationClass

scala> @AnnotationClass trait BaseTrait
defined trait BaseTrait

scala> class InheritingClass extends BaseTrait
defined class InheritingClass

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> typeOf[BaseTrait].typeSymbol.asClass.annotations.size
res1: Int = 1

scala> typeOf[InheritingClass].typeSymbol.asClass.annotations.size
res0: Int = 0

Is there a way to get the subclass to inherit the annotation of the parent?

like image 396
MrEnzyme Avatar asked Jul 05 '14 16:07

MrEnzyme


2 Answers

This is not possible to my knowledge. The only description of the scope of annotations in the docs reads:

An annotation clause applies to the first definition or declaration following it. More than one annotation clause may precede a definition and declaration. The order in which these clauses are given does not matter.

This probably means an annotation applies only to the first definition following it. Of course, you can make a helper method that checks the definitions on base classes:

def baseAnnotations[T : TypeTag] = typeOf[T].typeSymbol.asClass.baseClasses.flatMap(_.annotations)
baseAnnotations[InheritingClass].size //1
like image 78
Ben Reich Avatar answered Oct 10 '22 11:10

Ben Reich


While extending a trait does not inherit annotations, extending an abstract class DOES cause the annotations to be inherited.

like image 3
Snowbuilder Avatar answered Oct 10 '22 11:10

Snowbuilder