scala – WeakTypeTag v.TypeTag
发布时间:2020-12-16 19:16:57 所属栏目:安全 来源:网络整理
导读:在REPL中,我写出了 Reflection – TypeTags and Manifests的例子. 我对WeakTypeTag和TypeTag之间的区别感到困惑. scala import scala.reflect.runtime.universe._import scala.reflect.runtime.universe._ TypeTag scala def paramInfo[T](x: T)(implicit ta
在REPL中,我写出了
Reflection – TypeTags and Manifests的例子.
我对WeakTypeTag和TypeTag之间的区别感到困惑. scala> import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ TypeTag scala> def paramInfo[T](x: T)(implicit tag: TypeTag[T]): Unit = { | val targs = tag.tpe match { case TypeRef(_,_,args) => args } | println(s"type tag of $x has type arguments $targs") | } paramInfo: [T](x: T)(implicit tag: reflect.runtime.universe.TypeTag[T])Unit WeakTypeTag scala> def weakParamInfo[T](x: T)(implicit tag: WeakTypeTag[T]): Unit = { | val targs = tag.tpe match { case TypeRef(_,args) => args } | println(s"type tag of $x has type arguments $targs") | } weakParamInfo: [T](x: T)(implicit tag: reflect.runtime.universe.WeakTypeTag[T])Unit 运行一个简单,非详尽的例子 scala> paramInfo2(List(1,2,3)) type of List(1,3) has type arguments List(Int) scala> weakParamInfo(List(1,3) | ) type tag of List(1,3) has type arguments List(Int) 它们之间有什么区别? 解决方法
TypeTag保证你有一个具体的类型(即一个不包含任何类型参数或抽象类型成员的类型); WeakTypeTag没有.
scala> import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ scala> def foo[T] = typeTag[T] <console>:10: error: No TypeTag available for T def foo[T] = typeTag[T] ^ scala> def foo[T] = weakTypeTag[T] foo: [T]=> reflect.runtime.universe.WeakTypeTag[T] 但是,当然使用它时,它实际上无法获得调用该方法的泛型参数: scala> foo[Int] res0: reflect.runtime.universe.WeakTypeTag[Int] = WeakTypeTag[T] 如果所有参数都有TypeTag,则只能构建泛型类型的TypeTag: scala> def foo[T: TypeTag] = typeTag[List[T]] foo: [T](implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[List[T]] 如果你有一个具体类型的WeakTypeTag,它的行为应该与TypeTag相同(据我所知). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |