score:0

You can write in a macro

import scala.annotation.experimental
import scala.quoted.*

inline def printAnnotations[A]: Unit = ${printAnnotationsImpl[A]}

@experimental // because .typeRef is @experimental
def printAnnotationsImpl[A](using Quotes, Type[A]): Expr[Unit] = {
  import quotes.reflect.*

  val symbol = TypeTree.of[A].symbol
  println(symbol.caseFields.map(_.annotations)) // Case Class

  val companion = symbol.companionModule
  val methods = companion.declaredMethods
  // Annotated method argument
  println(methods.map(_.paramSymss.map(_.map(_.annotations)))) 

  // Annotated Type
  println(methods.collect(method => companion.typeRef.memberType(method) match {
    case lt: LambdaType => lt.paramTypes.collect {
      case at: AnnotatedType => at.annotation
    }
  }))

  '{()}
}

Then for

case class A(x: Int, @Annot("z1") y: String)
object A:
  def f1(x: Int, y: String @Annot("z2")): A = ???
  def f2(x: Int, @Annot("z3") y: String): A = ???

printAnnotations[A] will print

List(List(), List(Apply(Select(New(Ident(Annot)),<init>),List(Literal(Constant(z1))))))

List(List(List(List(), List())), List(List(List())), List(), List(List(List(), List())), List(List(List(), List(Apply(Select(New(Ident(Annot)),<init>),List(Literal(Constant(z3))))))), List(List()), List(List(List())))

List(List(), List(), List(Apply(Select(New(Ident(Annot)),<init>),List(Literal(Constant(z2))))), List(), List(), List())

Scala 3.1.3


Related Query

More Query from same tag