There\'s a handy implementation of asInstanceOfOpt
, a safe version of asInstanceOf
, given in the answer to How to write "asInstanceOfOption"
If you look in the Scala API the function singleType
takes a parameter of type AnyRef. I don't really know the background for this decision, but it seems you need to work around it. Instead of using the method singleType
I'd suggest using the classType
method which basically can make a manifest for any class. It'll take a bit more code, but it could look something like this:
class WithAsInstanceOfOpt(obj : Any) {
def asInstanceOfOpt[B : Manifest] : Option[B] = // [B : Manifest] is shorthand for [B](implicit m : Manifest[B])
if (Manifest.classType(manifest, obj.getClass) <:< manifest)
Some(obj.asInstanceOf[B])
else None
}