0

I need to implement Ad-hoc polymorphism, consider this code:

  trait BlockInputRequest

  case class StaticBlockInput(
    content: String
  ) extends BlockInputRequest

  case class StaticBlockOutput(
    content: String = ""
  )

  trait BlockProcessor[T] {
    def processBlock(request: T, project: String, userEmail: String, empty: Boolean = false)(implicit ec: ExecutionContext): Future[Any]
  }

  implicit val StaticBlockInputProcessor: BlockProcessor[StaticBlockInput] = new BlockProcessor[StaticBlockInput] {
    override def processBlock(request: StaticBlockInput, project: String, userEmail: String, empty: Boolean)(implicit ec: ExecutionContext): Future[Any] = {
      Future.successful(
        if (empty)
          StaticBlockOutput()
        else
          StaticBlockOutput(request.content)
      )
    }
  }

  implicit class BlockProcessorOps[T](request: T)(implicit ev: BlockProcessor[T]) {
    def processBlock(project: String, userEmail: String, empty: Boolean): Future[Any] = ev.processBlock(request, project, userEmail, empty)
  }

Then I have no problems to run something like:

StaticBlockInput("test string").processBlock("myProject","user@example.com",false)

But what if my input was created by reflection from some other part of code and actual class type is erased and all I have is an instance of generic type and manifest:

val manifest: Manifest[I <: BlockInputRequest] = ... // type is saved
val block: BlockInputRequest = ... // created using reflection
block.processBlock("myProject","user@example.com",false)

Is there a way I can resolve BlockProcessor? Or maybe I can use reflection again in some way?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Alex Z
  • 1
  • 1
  • 1
    That `Future[Any]` is ugly. Add `type R` to the typeclass and have `procesBlock` return `Future[R]`. Then add `type R = StaticBlockOutput` to `StaticBlockInputProcessor` – Tim Sep 03 '21 at 17:05
  • Resolving type classes at runtime using toolbox https://stackoverflow.com/questions/64308467/is-there-anyway-in-scala-to-get-the-singleton-type-of-something-from-the-more https://stackoverflow.com/questions/64045433/load-dataset-from-dynamically-generated-case-class https://stackoverflow.com/questions/64903163/implicit-resolution-fail-in-reflection-with-toolbox https://stackoverflow.com/questions/59348301/in-scala-2-or-3-is-it-possible-to-debug-implicit-resolution-process-in-runtime – Dmytro Mitin Sep 28 '21 at 13:50

0 Answers0