WeakTypeTag v。TypeTag

问题描述:

在REPL中,我写出了Reflection - TypeTags and Manifests的示例。WeakTypeTag v。TypeTag

我很困惑于WeakTypeTagTypeTag之间的差异。

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, 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) 

他们之间有什么区别?

+3

这是回答在http://*.com/questions/12218641/scala-what-is-a-typetag-and-how-do-i-use-it但不是最好的例子 – sschaef 2015-04-03 16:55:00

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