本文介绍了在Scala中将变量从存在类型的TypeCast转换为运行时类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此主题解决了在使用 Existential 类型时如何使用 TypeTag 获取运行时类型的类型参数。 另一个线程 a>解决了如何将变量强制转换为从 TypeTag 检索的运行时类型。

This thread addressed how to use TypeTag to get runtime type of type parameters when used with Existential type. Another thread addressed how to cast a variable to its runtime type retrieved from TypeTag.

我的问题建立在上述线程上(这两种情况的组合)。为了清楚起见,部分代码从两个线程复制。

My question builds on the aforementioned threads (kind of a combination of the two scenarios). Parts of the code is duplicated from the two threads for clarity.

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> def cast[A](a: Any, tt: TypeTag[A]): A = a.asInstanceOf[A]
cast: [A](a: Any, tt: reflect.runtime.universe.TypeTag[A])A

scala> abstract class Animal[T](implicit tt: TypeTag[T]) {
     |   val ttag = tt
     | }
defined class Animal

scala> case object Dog extends Animal[Int]
defined object Dog

scala> case object Cat extends Animal[String]
defined object Cat

scala> val aa: List[(Animal[_], Any)] = List((Dog, 5), (Cat, "stringgg"), (Dog, 2))                                                                                                               
aa: List[(Animal[_], Any)] = List((Dog,5), (Cat,stringgg), (Dog,2))

scala> aa(0)._1.ttag
res25: reflect.runtime.universe.TypeTag[_] = TypeTag[Int]

scala> aa(1)._1.ttag
res26: reflect.runtime.universe.TypeTag[_] = TypeTag[String]

scala> cast(aa(0)._2, aa(0)._1.ttag)
res27: Any = 5

scala> cast(aa(1)._2, aa(1)._1.ttag)
res28: Any = stringgg


b $ b

总之,最后两行: cast(value,TypeTag [_])总是返回类型 / code>。但我的目的是将这些值转换为存储在 Dog | Cat.ttag 中的正确类型,不幸的是,它不是 TypeTag [Int] / code>或 TypeTag [String] TypeTag [_] c> existsential 类型。是否有任何解决方案?

In short, the last two lines: cast(value, TypeTag[_]) always return a value of type Any. But my intention is to cast these values to the correct type stored in Dog|Cat.ttag, which, unfortunately, is not TypeTag[Int] or TypeTag[String] but TypeTag[_] due to usage of existential type. Is there any solution for it?

编辑1:

尽管字段 ttag 的类型为 TypeTag [_] ttag.tpe (但作为 reflect.runtime.universe.Type 的实例)。是否可以使用 typetag.tpe 来转换正确的类型?

Despite the field ttag is of type TypeTag[_], ttag.tpe does have the right "type" (but as an instance of reflect.runtime.universe.Type). Is it possible to use the typetag.tpe to cast to the right type?

推荐答案

您可以将cast方法更改为
def cast [A](a:Any,tt:TypeTag [_]):A = a.asInstanceOf [A] code>和

You could change the cast method as, def cast[A](a: Any, tt: TypeTag[_]): A = a.asInstanceOf[A] and

val x: Int = cast(aa(0)._2, aa(0)._1.ttag)

这篇关于在Scala中将变量从存在类型的TypeCast转换为运行时类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!