[英]In Scala, how to cast a value when a TypeTag is available
Given 特定
Any
Any
的值 TypeTag
corresponding to the desired type TypeTag
How can I cast the value 我怎样才能施展价值
Unfortunately, the following snippet doesn't compile 不幸的是,以下代码段无法编译
val v: Any = 123
val tag = typeTag[Int]
val i = v.asInstanceOf[t.tpe]
Use this 用这个
import scala.reflect.ClassTag
def getTypedArg[T: ClassTag](any: Any): Option[T] = {
any match {
case t: T => Some(t)
case invalid =>
None
}
}
Usage 用法
scala> getTypedArg[Int](5)
res1: Option[Int] = Some(5)
scala> getTypedArg[Int]("str")
res2: Option[Int] = None
Source: Retrieve class-name from ClassTag 来源: 从ClassTag中检索类名
EDIT-1 编辑-1
As asked by @Aki , it can be made to work with TypeTag
s too, with this hack 正如@Aki所要求的那样 ,也可以通过这种黑客攻击
TypeTag
import reflect.runtime.universe._
import scala.reflect.ClassTag
def typeToClassTag[T: TypeTag]: ClassTag[T] = {
ClassTag[T]( typeTag[T].mirror.runtimeClass( typeTag[T].tpe ) )
}
def getTypedArg2[T: TypeTag](any: Any): Option[T] = {
implicit val c: ClassTag[T] = typeToClassTag[T]
any match {
case t: T => Some(t)
case invalid =>
None
}
}
Reference: How to get ClassTag form TypeTag, or both at same time? 参考: 如何同时获取ClassTag表单TypeTag或两者?
You could write your own method that does the casting. 您可以编写自己的方法来执行转换。
(note that this method will never throw ClassCastExceptions) (请注意,此方法永远不会抛出ClassCastExceptions)
def cast[A](a: Any, tag: TypeTag[A]): A = a.asInstanceOf[A]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.