Mike Slinn

Scala Type Parameters, Implicit Manifests and Salat

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

This page is part of the posts collection, 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.

Shell
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:

Shell
findWithSeqNum(11)(Manifest.classType(classOf("com.micronautics.Blah"))

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

Shell
findWithSeqNum[Blah](11)

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

Shell
implicit val manifest: ClassManifest[Blah]
findWithSeqNum(11)

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

Shell
val mtype = "com.micronautics.Blah"
implicit val manifest = Manifest.classType(Class.forName(mtype))
findWithSeqNum(11)
* indicates a required field.

Please select the following to receive Mike Slinn’s newsletter:

You can unsubscribe at any time by clicking the link in the footer of emails.

Mike Slinn uses Mailchimp as his marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp’s privacy practices.