Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic generics in Scala

Tags:

generics

scala

I'm using a 3rd party library, and the signature of a method is:

def parse[A](input: String)(implicit mf: Manifest[A]): A = ...

I only know A at runtime. How do I call the parse method above with A represented as a string?

Is the only option matching against all my domain objects?

E.g.

object ParserHelper {
  def apply(clazz: String, arg: String) = clazz match {
    case "DomainObjectA" => parse[DomainObjectA](arg)
    case "DomainObjectB" => parse[DomainObjectB](arg)
    case _ => throw new RuntimeException("Domain class %s not mapped" format clazz)
  }
}

...and then calling ParserHelper("com.example.DomainObjectA", "some argument") ?

I.e. how do I call parse[???]("") where ??? is dynamically constructed at run-time from a string like "com.example.SomeDomainObject"?

like image 424
opyate Avatar asked Sep 20 '25 14:09

opyate


1 Answers

I don't think that is possible. You need to know something [A] at compile time that you only know at runtime.

like image 105
bruno conde Avatar answered Sep 22 '25 05:09

bruno conde