简体   繁体   English

scala的ClassTag和TypeTag之间的区别

[英]Difference between scala's ClassTag and TypeTag

According to scala doc,TypeTag contains more information than ClassTag. 根据scala doc,TypeTag包含的信息比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. 在我看来,TypeTag可以比ClassTag做更多的事情,比如将编译时的类型参数信息带到运行时等。

However, the following example shows that ClassTag can do the job, while the TypeTag not. 但是,以下示例显示ClassTag可以完成工作,而TypeTag则不能。 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. 只有ClassTag会将模式匹配引导到None (这是预期的行为),前两个注释行将会出现Some分支。

It seems that ClassType can reflect on object's type on runtime, while Type Tag can't. 似乎ClassType可以在运行时反映对象的类型,而Type Tag则不能。 But isn't TypeTag a superset of ClassTag ? I would like to know the explanation as detailed as possible. 但TypeTag不是ClassTag的超集吗?我想尽可能详细地了解解释。 Thank you. 谢谢。

this page will help you! 这个页面会对你有所帮助!
take a look :) 看一看 :)

https://medium.com/@sinisalouc/overcoming-type-erasure-in-scala-8f2422070d20 https://medium.com/@sinisalouc/overcoming-type-erasure-in-scala-8f2422070d20

add more detail, since only link answer is not appropriate... 添加更多细节,因为只有链接答案不合适...

ClassTag : runtime information about value, but not good with generic style ClassTag:有关值的运行时信息,但对通用样式不太好
TypeTag : runtime information about type TypeTag:有关类型的运行时信息

eg 例如

object Test extends App {

  import scala.reflect.ClassTag
  def func[T : ClassTag](o: Any): Unit = {
    o match {
      case x: T => println(x)
      case _ => println(None)
    }
  }
  func[List[String]](List(1, 2, 3)) // List(1, 2, 3), not None!!! with List[String] type parameter... ClassTag only recognize List scale, not List[T]

  import scala.reflect.runtime.universe._
  def func2[T](o: T)(implicit tag: TypeTag[T]): Unit = {
    tag.tpe match {
      case TypeRef(utype, usymbol, args) => println(args.toString)
      case _ => println(None)
    }
  }
  func2(List(1, 2, 3)) // List(Int)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM