jeudi 27 avril 2017

Get the Runtime Type of a Generic Type in Scala

I have the following trait:

      trait CSVRowParser[A] {
        def parse(row: Seq[String]): Try[A]
      }

      object CSVRowParser {
        implicit def all[A, H <: HList](implicit gen: Generic.Aux[A, H],
          read: CSVRowReader[H]): CSVRowParser[A] = new CSVRowParser[A] {
          def parse(row: Seq[String]): Try[A] = {
            read.from(row).map(gen.from)
          }
        }
        def apply[A](implicit ev: CSVRowParser[A]): CSVRowParser[A] = ev
  }

I have another class called CSVReader:

class CSVReader[A: CSVRowParser] {

   def parse(path: String): ReaderWithFile[A] = ReaderWithFile[A](path)

   case class ReaderWithFile[B: CSVRowParser](path: String) {
    ...
    // how can I here identify the type of B?
   }

}

I then do the call like this:

  def apply[A: CSVRowParser] = new CSVReader[A]

  val reader = apply[Address]
  val withCustomConfig: Seq[Address] = reader parse "/csv-parser/address.csv" using CSVParserConfig(Pipe)

How can I get the runtime type of A inside the ReaderWithFile case class?





Aucun commentaire:

Enregistrer un commentaire