简体   繁体   English

在Scala中,如何在TypeTag可用时转换值

[英]In Scala, how to cast a value when a TypeTag is available

Given 特定

  • a value of type Any 类型为Any的值
  • a 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.

相关问题 在Scala中,如何创建TypeTag [Map [A​​,B]],而只有TypeTag [A]和TypeTag [B]可用? - In Scala, How to create TypeTag[Map[A,B]], while only TypeTag[A] and TypeTag[B] are available? 为什么嵌套实例化中没有TypeTag(由scala代码运行符解释)? - Why there is no TypeTag available in nested instantiations (when interpreted by scala code runner)? Scala-没有TypeTag可用当使用案例类尝试获取TypeTag时发生异常吗? - Scala - No TypeTag Available Exception when using case class to try to get TypeTag? 没有 TypeTag 可用于案例 class 使用 scala 3 和火花 3 - No TypeTag available for a case class using scala 3 with spark 3 同时指定TypeTag时如何指定Scala类型参数约束 - How to specify scala type parameter constraint when also specifying TypeTag 带有scala2.10.6的spark1.6.2没有可用的TypeTag - spark1.6.2 with scala2.10.6 No TypeTag available Scala编译器在使用泛型的方法中说“没有TypeTag可用于T” - Scala compiler says “No TypeTag available for T” in method using generics Spark Scala API:官方示例中spark.createDataFrame中没有typeTag - Spark Scala API: No typeTag available in spark.createDataFrame in official example 具有“No TypeTag available”的Scala / Spark应用程序“def main”样式App中的错误 - Scala/Spark App with “No TypeTag available” Error in “def main” style App 在Scala中,如何获取类方法的返回的TypeTag? - In Scala, How to get the returned TypeTag of a class method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM