请参阅以下代码:
def createOption[T: TypeTag](referentialData: Any) : Option[T] = {
Option(referentialData) match {
case Some(camelMessage: CamelMessage) => {
Option(camelMessage.body) match {
case Some(option: T) => Some(option)
case _ => None
}
}
case _ => None
}
}
基本上,如果Option[T]
非空且类型为T,我希望返回camelMessage.body
。
Option(referentialData)
的使用实际上是referentialData != null
同样适用于Option(camelMessage.body)
如何使用TypeTag确定camelMessage.body
是否为T类型。
(我知道这可以重写为不使用TypeTags和Options但是我想学习如何使用TypeTags所以请不要重写,谢谢!)
修改
我尝试了一种新方法,因为无法找到上述解决方案,但无法使这一方法工作:
def createOption[T](referentialData: Any) : Option[T] = {
Option(referentialData) match {
case Some(option) => Try(option.asInstanceOf[T]).toOption
case _ => None
}
}
当我使用createOption[Long]("test")
调用此内容时,我假设返回None
,但我获得了Some(String)
我在哪里错了?
答案 0 :(得分:1)
这是this one的副本。
但您想尝试使用ClassTag
来显示限制:
scala> def f[A: ClassTag](x: Any): Option[A] = x match {
| case y: A => println("OK"); Some(y) ; case _ => println("Nope"); None }
f: [A](x: Any)(implicit evidence$1: scala.reflect.ClassTag[A])Option[A]
scala> f[String]("foo")
OK
res0: Option[String] = Some(foo)
scala> f[Long](2L)
Nope
res1: Option[Long] = None
scala> f[java.lang.Long](new java.lang.Long(2L))
OK
res2: Option[Long] = Some(2)
scala> def f[A: TypeTag](x: Any): Option[A] = Option(x) match {
| case Some(y: A) => println("OK"); Some(y) ; case _ => println("Nope"); None }
<console>:51: warning: abstract type pattern A is unchecked since it is eliminated by erasure
case Some(y: A) => println("OK"); Some(y) ; case _ => println("Nope"); None }
^
f: [A](x: Any)(implicit evidence$1: reflect.runtime.universe.TypeTag[A])Option[A]