我需要实现 Ad-hoc 多态性,请考虑以下代码:
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)
}
然后我运行类似的东西没有问题:
StaticBlockInput("test string").processBlock("myProject","user@example.com",false)
但是,如果我的输入是通过代码的其他部分的反射创建的,并且实际的类类型被删除了,我所拥有的只是一个泛型类型和清单的实例:
val manifest: Manifest[I <: BlockInputRequest] = ... // type is saved
val block: BlockInputRequest = ... // created using reflection
block.processBlock("myProject","user@example.com",false)
有什么办法可以解决BlockProcessor
吗?或者也许我可以以某种方式再次使用反射?