Is it possible to get the type name of a generic class in Scala? I know this isn’t possible in Java with type erasure, but I was hoping that Scala would be a different case.
Currently I have to do something similar to this:
trait Model
case class User(id: String) extends Model
def fromMap[M<:Model : Manifest](data: Map[String, String], modelType: String) = {
modelType match {
case "user" => User(data.get("id").get)
}
}
val user = fromMap[User](Map("id" -> "id1"), "user")
Obviously it would be easier if I could work out “user” without having to have it passed in.
Class name can be retrieved from a Manifest (or a ClassManifest) with
manifest.erasure.getName(erasure is the Class instance). For instanceEdit : Seen Derek’s answer, which makes this stuff with erasure.getName look rather stupid. I didn’t consider toString. Still I hope what follows may be of interest
The difference between using
ClassManifestandManifestis that in theManifestfor a generic class, the type parameter are guaranteed to be available, while they are best effort inClassManifest(compare signatures oftypeParametersin both classes). The drawback of this guarantee is that aManifestmight not be implicitly available where aClassManifestwould be.Have you considered using typeclasses instead?
This way, calls to
fromMapwill compile only if aBuilderis available for this particular class, rather than fail with aMatchError.