[英]Scala: Using a TypeTag to match on a Some's type
See the following code: 请参见以下代码:
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
}
}
Basically I am looking to return an Option[T]
if camelMessage.body
is non-null and of type T. The uses of Option(referentialData)
is effectively referentialData != null
Likewise for Option(camelMessage.body)
基本上,如果
camelMessage.body
为非null且类型为Option[T]
则我希望返回Option[T]
camelMessage.body
Option(referentialData)
的使用实际上是referentialData != null
对于Option(camelMessage.body)
How do I use the TypeTag to determine if camelMessage.body
is of type T. 如何使用TypeTag确定
camelMessage.body
是否为T类型。
(I know this can be re-written to not use TypeTags and Options but I want to learn how to use TypeTags so please no suggestions to re-write, thanks!) (我知道可以重写为不使用TypeTags和Options,但是我想学习如何使用TypeTags,所以请不要提出任何重写建议,谢谢!)
Edit 编辑
I tried a new approach as could not find a solution for the above, but could not get this one to work either: 我尝试了一种新方法,因为找不到上述解决方案,但也无法使该方法正常工作:
def createOption[T](referentialData: Any) : Option[T] = {
Option(referentialData) match {
case Some(option) => Try(option.asInstanceOf[T]).toOption
case _ => None
}
}
When I invoke this using createOption[Long]("test")
I was presuming to get a None
back, but instead I got a Some(String)
Where am I going wrong here? 当我使用
createOption[Long]("test")
调用此createOption[Long]("test")
时,我想得到的是None
,但是我得到的是Some(String)
我在哪里出错了?
This is a duplicate of this one . 这是一个重复的这一个 。
But you want to try it with ClassTag
to show the limitation: 但是您想尝试使用
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.