tribbloid
tribbloid

Reputation: 3838

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

I'm using apache Spark and one of my subroutine is to check if T: ClassTag of an RDD[T: ClassTag] is a subclass of Map.

I've checked many source on scala reflection and they all suggest the following code:

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

however the classTag function seems to be missing, I only see typeOf and weakTypeOf which obviously doesn't work here (because of type erasure: ClassTag of an RDD carries far less information than a TypeTag). Is it moved somewhere else in a later scala version? I'm using 2.10.4

Thanks a lot!

Upvotes: 0

Views: 517

Answers (1)

dk14
dk14

Reputation: 22374

It's in scala.reflectpackage

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

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

See the most modern documentation

For subtyping check you shoud use typeTag, like:

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

You can obtain TypeTag in the same way as ClassTag. If you want to obtain TypeTag from ClassTag with unerased type:

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]

If you just need to check subtyping between two known types:

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

Upvotes: 1

Related Questions