1

I am working in Scala programming language. We are using annotations to apply some metadata on class fields

e.g.

Annotation class

case class Address(city: City, zip: Zip)  extends StaticAnnotation //City and Zip are Enumeration types

Class that uses annotation

case class Person
(
  @Address(City.LA, Zip.SomeZip)
  Field: String
)

Now I want to retrieve the value of city (which is LA) and zip (which is SomeZip) as a string, regardless of the order of the arguments.

what I have tried is this

val fields = typeOf[Person].typeSymbol.info.decls
      .find(d => d.isMethod && d.asMethod.isPrimaryConstructor)
      .get.typeSignature.paramLists.head
    
for(annotation <- field.annotations){
    println(annotation.toString) //returns Address(City.LA, Zip.SomeZip)
}

the above code works and returns the string, which I can parse and retrieve the desired values as shown above. But it works only when the arguments are provided in true order -> (City, Zip) but not the other way around. e.g.

@Address(zip = Zip.SomeZip, city = City.LA) // returns Address(x$4, x$3)

How can i retrieve the correct values (enum strings if possible -> "LA", "SomeZip") for each arg?

Ano
  • 11
  • 2
  • Why are you using an annotation to store this, as opposed to nesting the Address case class inside Person? – Nick Feb 17 '21 at 00:25
  • this is just an example, the actual fields and annotations are different. I gave city and zip example so that its easy to read – Ano Feb 17 '21 at 01:16
  • if you use `shapeless` library, then you can use `Annotations` typeclass which will give you access to your Address case class and then with another shapeless typeclass (e.g. LabelledGeneric) you can get access to the fields names and values – jker Feb 17 '21 at 11:48
  • @jker do you think you can provide example? I went thru this example: [link](https://stackoverflow.com/questions/54412106/shapeless-and-annotations). it prints "sha1" but I don't know how to retrieve that value for further use. Also in that example I am not sure how can i implement more cases. e.g. haw can i handle more classes then just "MyAnnotation"? – Ano Feb 18 '21 at 21:56
  • https://stackoverflow.com/questions/55032173/how-to-use-named-arguments-in-scala-user-defined-annotations https://stackoverflow.com/questions/14034142/how-do-i-access-default-parameter-values-via-scala-reflection – Dmytro Mitin Jul 04 '21 at 10:48

0 Answers0