WeakTypeTag 与 TypeTag

2024-01-08

在 REPL 中,我写下了以下示例反射 - 类型标签和清单 http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html.

我对之间的区别感到困惑WeakTypeTag and 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

弱类型标签

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, 2, 3) has type arguments List(Int)

scala> weakParamInfo(List(1,2,3)
     | )
type tag of List(1, 2, 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泛型类型,如果你有TypeTags 代表所有参数:

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(据我所知)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WeakTypeTag 与 TypeTag 的相关文章

随机推荐