如何写asInstanceOfOpt [T]其中T <:Any

Mat*_*t R 9 scala

在Scala中如何编写"asInstanceOfOption"的答案中给出了asInstanceOfOpt一个安全版本的方便实现.看来,Scala 2.9.1,这个解决方案现在只适用于AnyRef:asInstanceOf

class WithAsInstanceOfOpt(obj: AnyRef) {
  def asInstanceOfOpt[B](implicit m: Manifest[B]): Option[B] =
    if (Manifest.singleType(obj) <:< m)
      Some(obj.asInstanceOf[B])
    else
      None
}
Run Code Online (Sandbox Code Playgroud)

这可以改写为支持Any吗?

Jen*_*olm 1

如果您查看 Scala API,就会发现该函数singleType采用 AnyRef 类型的参数。我真的不知道这个决定的背景,但看来你需要解决这个问题。singleType我建议使用基本上classType可以为任何类制作清单的方法,而不是使用该方法。这需要更多的代码,但它可能看起来像这样:

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
}
Run Code Online (Sandbox Code Playgroud)