5

I would like to apply some functions to fields in a case class. A field that has to be "transformed" is annotated using Annot. I am trying to use Everywhere and a Poly1. At the moment I am able to apply the transformation function to all the fields but I am not able to "pass" the information about the annotated fields.

import shapeless._

object Test {
  case class Annot(
    fieldType: String
  ) extends scala.annotation.StaticAnnotation

  case class Address(
    street: String,
    isCapital: Boolean
  )
  case class Person(
    @Annot("TypeA") lastName: String,
    firstName: String,
    isTall: Boolean,
    address: Address
  )

  def transformationMethod(element: String, fieldType: String): String = ???

  object Transformer extends Poly1 {
    implicit def someStringCase: Case.Aux[String, String] = at {
      case e => {
        transformationMethod(e, "Name")
      }
    }
    //other methods ..
  }

  def traverseAndModify[T](
    expr: T
  )(implicit e: Everywhere[Transformer.type, T] { type Result = T }): T = e(expr)


  //Usage
  val person = Person("LASTName", "FIRSTName", true, Address("My home address", true))
  val modified : Person = traverseAndModify[Person](person)

}

I am wondering how to modify "everywhere" to also pass annotations to the poly function. So I would like something similar to this in the Poly

object AnnotatedTransformer extends Poly1 {
  implicit def someStringCase: Case.Aux[(String, Some[Annot]), String] = at {
    case (e, Some(Annot(fieldType))) => {
     transformationMethod(e, fieldType)
    }
  }
}
dadesan89
  • 51
  • 3
  • Standard `everywhere` will not help. It traverses nested structure looking at types of nodes. And annotation in `@Annot("TypeA") lastName: String` annotates not field type but field itself (annotated type would look like `lastName: String @Annot("TypeA")`). But even if types were annotated `everywhere` just doesn't expect that it should distinguish annotated and ordinary things. So you'd have to implement this yourself using deep traversing ([1](https://github.com/milessabin/shapeless/blob/master/examples/src/main/scala/shapeless/examples/deephlister.scala) – Dmytro Mitin Aug 09 '19 at 15:28
  • [2](https://stackoverflow.com/questions/49710536/deriving-nested-shapeless-lenses-using-only-a-type/) [3](https://stackoverflow.com/questions/25923974/weird-behavior-trying-to-convert-case-classes-to-heterogeneous-lists-recursively)) and `shapeless.Annotations` [4](https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/annotation.scala#L102). – Dmytro Mitin Aug 09 '19 at 15:29

0 Answers0