如何编写 asInstanceOfOpt[T] 其中 T <: Any [英] How to write asInstanceOfOpt[T] where T <: Any
本文介绍了如何编写 asInstanceOfOpt[T] 其中 T <: Any的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
asInstanceOfOpt
有一个方便的实现,它是 asInstanceOf
的安全版本,在 如何编写asInstanceOfOption";在 Scala 中.看来,Scala 2.9.1,这个解决方案现在只适用于 AnyRef:
There's a handy implementation of asInstanceOfOpt
, a safe version of asInstanceOf
, given in the answer to How to write "asInstanceOfOption" in Scala. It appears that, Scala 2.9.1, this solution now only works with AnyRef:
class WithAsInstanceOfOpt(obj: AnyRef) {
def asInstanceOfOpt[B](implicit m: Manifest[B]): Option[B] =
if (Manifest.singleType(obj) <:< m)
Some(obj.asInstanceOf[B])
else
None
}
可以重写以支持 Any 吗?
Can this be rewritten to support Any?
推荐答案
你可以使用 shapeless's 可从 Miles Sabin 输入:
You could use shapeless's Typeable from Miles Sabin:
它处理原语和装箱:
scala> import shapeless._; import syntax.typeable._
import shapeless._
import syntax.typeable._
scala> 1.cast[Int]
res1: Option[Int] = Some(1)
scala> 1.cast[String]
res2: Option[String] = None
scala> "hello".cast[String]
res4: Option[String] = Some(hello)
scala> "foo".cast[Int]
res5: Option[Int] = None
您可以在此处查看源代码以了解其编写方式:
You can see the source here to see how it's written:
https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/typeable.scala
这篇关于如何编写 asInstanceOfOpt[T] 其中 T <: Any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文