为什么缺少函数 scala.reflect.runtime.universe.classTag[T]?

Why function scala.reflect.runtime.universe.classTag[T] is missing?

我正在使用 apache Spark,我的子例程之一是检查 RDD[T: ClassTag] 的 T: ClassTag 是否是 Map 的子类。

我检查了很多关于 scala 反射的资源,他们都建议使用以下代码:

import scala.reflect.runtime.universe._
if classTag[T] <:< classTag[Map[_,_]] {do something...}

然而 classTag 函数似乎丢失了,我只看到了 typeOf 和 weakTypeOf 这显然在这里不起作用(因为类型擦除:RDD 的 ClassTag 携带的信息远少于 TypeTag)。它是否在以后的 Scala 版本中移动到其他地方?我正在使用 2.10.4

非常感谢!

它在scala.reflect

scala> import scala.reflect._
import scala.reflect._

scala> classTag[Option[Int]]
res45: scala.reflect.ClassTag[Option[Int]] = scala.Option

看最现代的documentation

对于子类型检查,您应该使用 typeTag,例如:

import scala.reflect.runtime.universe._
scala> typeTag[Int].tpe <:< typeTag[Any].tpe
res54: Boolean = true

scala> typeTag[Int].tpe <:< typeTag[Boolean].tpe
res55: Boolean = false

你可以获得TypeTag,方法与ClassTag相同。如果你想从 ClassTag 中获取 TypeTag 并且类型为:

scala> def getTypeTag[T: TypeTag](ct: ClassTag[T]) = typeTag[T]
getTypeTag: [T](ct: scala.reflect.ClassTag[T])(implicit evidence: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[T]

scala> getTypeTag(classTag[Int])
res52: reflect.runtime.universe.TypeTag[Int] = TypeTag[Int]

如果您只需要检查两个已知类型之间的子类型:

scala> typeOf[Int] <:< typeOf[Boolean]
res56: Boolean = false