问题描述
在 REPL 中,我正在写出来自 Reflection 的示例 -类型标签和清单.
In the REPL, I'm writing out the examples from Reflection - TypeTags and Manifests.
我对 WeakTypeTag
和 TypeTag
之间的区别感到困惑.
I'm confused by the difference between WeakTypeTag
and TypeTag
.
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
类型标签
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, 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
没有.
TypeTag
guarantees that you have a concrete type (i.e. one which doesn't contain any type parameters or abstract type members); WeakTypeTag
does not.
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]
但当然,当像这样使用时,它实际上无法为您提供调用该方法的通用参数:
But of course it can't actually get you the generic parameters the method is called with when used like this:
scala> foo[Int]
res0: reflect.runtime.universe.WeakTypeTag[Int] = WeakTypeTag[T]
如果所有参数都具有 TypeTag
,则只能构建泛型类型的 TypeTag
:
You can only build a TypeTag
of a generic type if you have TypeTag
s for all parameters:
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
相同(据我所知).
If you have a WeakTypeTag
of a concrete type, it should behave the same as a TypeTag
(as far as I know).
这篇关于WeakTypeTag 与 TypeTag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!