Mike Slinn
Mike Slinn

Scala Type Parameters, Implicit Manifests and Salat

Published 2012-08-02.
Time to read: 1 minutes.

This site is categorized under Scala.

Type parameters provide types for constructing any arguments that are implicit manifests.

This helps when working with Salat. In the following code, dbo is a com.mongodb.DBObject, perhaps retrieved as the result of a find(). Salat uses _typeHint to store the fully qualified name of the persisted class; this property is returned as one of the properties of dbo. The call to Salat's grater() method converts dbo into the desired type. The type is constrained using a lower bound to be a subclass of PubSubAction.

def findWithSeqNum[T <: PubSubAction](seqNum: Long)
    (implicit manifest: Manifest[T]): Option[T] = {
  val klass = manifest.erasure.asInstanceOf[Class[T]]
  val item = myCollection.findOne(
    MongoDBObject("seqNum" -> seqNum, "_typeHint" -> klass.getName))
  item match {
    case Some(dbo: DBObject) =>
      Some(grater(ctx, Manifest.classType(klass)).asObject(dbo))
case None => None } }

When called as follows, the type parameter need not be provided because there is an explicit manifest argument:


When called as follows, the type parameter provides the value for constructing the implicit manifest argument:


Of course, you can also explicitly define an implicit manifest at any scope that you desire:

implicit val manifest: ClassManifest[Blah]

If the type of the manifest is dynamic (only known at runtime), you can define manifest this way:

val mtype = "com.micronautics.Blah"
implicit val manifest = Manifest.classType(Class.forName(mtype))