dimanche 23 octobre 2016

Difference between scala's ClassTag and TypeTag

According to scala doc,TypeTag contains more information than ClassTag. It seems to me that TypeTag can do more things than ClassTag, like bring the type parameter information of compile time to runtime, etc.

However, the following example shows that ClassTag can do the job, while the TypeTag not. I want to understand why.

import scala.reflect.ClassTag
import scala.reflect.runtime.universe.TypeTag
// def func[T](o: Any): Unit = {
// def func[T : TypeTag](o: Any): Unit = {
def func[T : ClassTag](o: Any): Unit = {
  o match {
    case x: T => println(Some(x))
    case _ => println(None)
  }spark
}
func[Map[Int, Int]](List(1, 2, 3))

Only ClassTag will lead the pattern matching to None (which is the expected behavior), the first two commented lines will come up with Some branch.

It seems that ClassType can reflect on object's type on runtime, while Type Tag can't. But isn't TypeTag a superset of ClassTag ? I would like to know the explanation as detailed as possible. Thank you.





Aucun commentaire:

Enregistrer un commentaire