Scala 3 Macros: How to Read Annotations :: Jun 25, 2023
This post will examine how to read class & field StaticAnnotations from a Scala 3 Macro.
Types of Annotations
Scala has a few different types of annotations. The base class of all annotations is Annotation, but developers should extend one of the subtypes. StaticAnnotations are persisted to the class file, and can be read from macros. ConstantAnnotation extends StaticAnnotation and requires all parameters to be compile-time constants. Finally, MacroAnnotation is an experimental annotation that can transform & create new definitions.
Reading Annotations on a Class
Assume we have the following SqlName StaticAnnotation, applied to a class:
We can read the sqlName value with the following macro:
In a different file:
Reading Annotations on a Field
Let’s take the same SqlName annotation as above, and apply it on a field:
We can read the sqlName value with the following macro: