scalascala-reflectscala-generics

How to load implicit Manifest from polymorphic type field


I am trying to build an interpreter for my ADT but I don't know how to solve the problem of loading the implicit manifests in a nice way

sealed trait Polymorphic[T]
case class Type1[T: Manifest](field1: T) extends Polymorphic[T]
case class Type2[T: Manifest, V: Manifest](field1: T, field2:V) extends Polymorphic[T] {
    def vManifest: Manifest[V] = manifest[V]
}

object Interpreter {
    def eval[T: Manifest](polymorphic: Polymorphic[T]): T = {
      polymorphic match {
        case Type1(field) =>
          ???
        case value: Type2[T, _] =>
          implicit val vManifest = value.vManifest
          evalType2(value)
      }
    }

    def evalType2[T:Manifest, V:Manifest](type2: Type2[T,V]): T = ???
}

This was the best solution I could create but I don't like that I had to create that vManifest function to be able to load the manifest in the eval.

Is there a better way to do this?


Solution

  • Remember T: Manifest is just a shorthand way to write an implicit constructor argument. If you want to make this argument visible to outside, just make it a val:

    case class Type1[T](field1: T)(implicit val tManifest: Manifest[T]) extends Polymorphic[T]
    case class Type2[T](field1: T, field2: V)(implicit val tManifest: Manifest[T], val vManifest: Manifest[V]) extends Polymorphic[T]
    

    (and most likely these days, you want ClassTag or TypeTag rather than Manifest).