What I'm trying to do is: get an implicit instance from the class name. The main problem that I can't get an implicit instance for a class type that created at runtime.
What I have:
trait Base
case class A() extends Base
case class B() extends Base
trait Worker[T <: Base] {
def foo(t: T): Unit
}
implicit val workerA = new Worker[A] {
def foo(a: A): Unit = ??? // do some A specific work
}
implicit val workerB = new Worker[B] {
def foo(b: B): Unit = ??? // do some B specific work
}
What I want to do: somehow get an implicit instance from the class name.
trait TypeHolder {
type Typed <: Base
}
def getClassType(className: String): TypeHolder = className match {
case "A" => new TypeHolder {
type Typed = A
}
case "B" => new TypeHolder {
type Typed = B
}
}
def getWorker(typeHolder: TypeHolder)(implicit worker: Worker[typeHolder.Typed]): Worker[typeHolder.Typed] = worker
val className: String = ConfigFactory.load().getString("class-name")
val worker = getWorker(getClassType(className))
Error: could not find implicit value for parameter worker: Worker[typeHolder.Typed] val worker = getWorker(getClassType(className))
That's impossible.
Implicit resolution is resolved at compile time: it can't be influence by a runtime value.