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

时间:2015-01-22 08:07:27

标签: scala reflection

我正在使用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

非常感谢!

1 个答案:

答案 0 :(得分:1)

它在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。如果您想从TypeTag获取ClassTag未选择的类型:

scala> def getTypeTag[T: TypeTag](ct: ClassTag[T]) = typeTag[T]
getTypeTag: [T](ct: scala.reflect.ClassTag[T])(implicit evidence$1: 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
相关问题