scala> def max[T : Comparator] (a:T, b:T) = { … }
T : Comparator
就表示存在一个 Comparator[T]
类型的隐式值。import scala.reflect.runtime.universe._ def meth[A : TypeTag](xs: List[A]) = typeOf[A] match {
case t if t =:= typeOf[String] => "list of strings"
case t if t <:< typeOf[Foo] => "list of foos"} scala> meth(List("string"))
res67: String = list of strings scala> meth(List(new Foo))
res68: String = list of foos
There exist three different types of TypeTags:
scala.reflect.api.TypeTags#TypeTag
. A full type descriptor of a Scala type. For example, aTypeTag[List[String]]
contains all type information, in this case, of typescala.List[String]
.scala.reflect.ClassTag
. A partial type descriptor of a Scala type. For example, aClassTag[List[String]]
contains only the erased class type information, in this case, of typescala.collection.immutable.List
.ClassTag
s provide access only to the runtime class of a type. Analogous toscala.reflect.ClassManifest
.scala.reflect.api.TypeTags#WeakTypeTag
. A type descriptor for abstract types (see corresponding subsection below).
2. 如何在代码体中获取TypeTag? 当显式使用隐式参数时,可以直接使用这个隐式参数;当使用context bounds时,使用接受相关隐式参数的方法,比如typeOf。
- via the Methods
typeTag
,classTag
, orweakTypeTag
- Using an Implicit Parameter of Type
TypeTag[T]
,ClassTag[T]
, orWeakTypeTag[T]
- Using a Context bound of a Type Parameter