How to write asInstanceOfOpt[T] where T <: Any

后端 未结 3 847
借酒劲吻你
借酒劲吻你 2021-02-06 03:41

There\'s a handy implementation of asInstanceOfOpt, a safe version of asInstanceOf, given in the answer to How to write "asInstanceOfOption"

3条回答
  •  误落风尘
    2021-02-06 04:05

    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
    }
    

提交回复
热议问题