加入收藏 | 设为首页 | 会员中心 | 我要投稿 网站开发网_安阳站长网 (https://www.0372zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

scala reflection-Mirrors,ClassTag,TypeTag and WeakTypeTag

发布时间:2016-10-29 21:13:36 所属栏目:教程 来源:站长网
导读:副标题#e# 反射reflection是程序对自身的检查、验证甚至代码修改功能。反射可以通过它的Reify功能来实时自动构建生成静态的Scala实例如:类(class)、方法(method)、表达式(expression)等。或者动态跟踪当前程序运算事件如:方法运算(method invocati

可以看到,虽然compiler产生并提供了TypeTag隐式参数evidence$3,但运算结果并不正确,这是为什么呢?从这个例子可以证实了ClassTag和TypeTag最大的区别:ClassTag在运算时提供了一个实例的类型信息,而TypeTag在运算时提供了一个类型的完整信息。我们只能用ClassTag来比较某个值的类型,而在运算时用TypeTag只能进行类型对比。extract中elem是List里的一个元素,是个值,所以只能用ClassTag来判别这个值的类型。如果使用TypeTag的话我们只能实现像下面示例中的类型对比:

 1  def meth[T: ru.TypeTag](xs: List[T]) = ru.typeTag[T].tpe match {
 2     case t if t =:= ru.typeOf[Int] => "list of integer"
 3     case t if t =:= ru.typeOf[List[String]] => "list of list of string"
 4     case t if t =:= ru.typeOf[Set[List[Int]]] => "list of set of list of integer"
 5     case _ => "some other types"
 6  }     //> meth: [T](xs: List[T])(implicit evidence$5: ru.TypeTag[T])String
 7  meth(List(1,2,3))                                //> res10: String = list of integer
 8  meth(List("a","b"))                              //> res11: String = some other types
 9  meth(List(List("a","a")))                        //> res12: String = list of list of string
10  meth(List(Set(List(1,20))))                      //> res13: String = list of set of list of integer

我们只能在运算时对T进行类型匹配。总结以上分析,ClassTag与TypeTag有下面几点重要区别:

1、ClassTag不适用于高阶类型:对于List[T],ClassTag只能分辨是个List,但无法获知T的类型。所以ClassTag不能用来解决类型擦拭(type erasure)问题

2、TypeTag通过完整的类型信息可以分辨高阶类型的内部类型,但它无法提供运算时(runtime)某个实例的类型。总的来说:TypeTag提供了runtime的类型信息,ClassTag提供runtime实例信息(所以ClassTag就像typeclass,能提供很多类型的隐型实例)

那么这个WeakTypeTag又是用来干什么的?它与TypeTag又有什么分别呢?如果我们把上面的meth函数改成使用WeakTypeTag:

 1  def meth[T: ru.WeakTypeTag](xs: List[T]) = ru.weakTypeTag[T].tpe match {
 2     case t if t =:= ru.typeOf[Int] => "list of integer"
 3     case t if t =:= ru.typeOf[List[String]] => "list of list of string"
 4     case t if t =:= ru.typeOf[Set[List[Int]]] => "list of set of list of integer"
 5     case _ => "some other types"
 6  }      //> meth: [T](xs: List[T])(implicit evidence$5: ru.WeakTypeTag[T])String
 7  meth(List(1,2,3))                                //> res10: String = list of integer
 8  meth(List("a","b"))                              //> res11: String = some other types
 9  meth(List(List("a","a")))                        //> res12: String = list of list of string
10  meth(List(Set(List(1,20))))                      //> res13: String = list of set of list of integer

(编辑:网站开发网_安阳站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!