了解Scala中的TypeTag

时间:2018-01-22 14:40:39

标签: scala types

我有以下代码:

trait TypeTaggedTrait[Self] { self: Self =>

        /**
            * The representation of this class's type at a value level.
            *
            * Useful for regaining generic type information in runtime when it has been lost (e.g. in actor communication).
            */
          val selfTypeTag: TypeTag[Self]

          /**
            * Compare the given type to the type of this class
            *
            * Useful for regaining generic type information in runtime when it has been lost (e.g. in actor communication).
            *
            * @return true if the types match and false otherwise
            */
          def hasType[Other: TypeTag]: Boolean =
            typeOf[Other] =:= typeOf[Self]

    }

当我这样做时,hasType[Other: TypeTag]方法的等价物是什么?:

typeOf[Other] =:= selfTypeTag.tpe

和做什么一样?:

typeOf[Other] =:= typeOf[Self]

该类型似乎只是Type某些Type的反映表示。

1 个答案:

答案 0 :(得分:1)

好吧,我想我设法解决了这个问题。从TypeTag的Scala文档中获取提示,这个版本:

import scala.reflect.runtime.universe._

def paramInfo[T](x: T)(implicit tag: TypeTag[T]): Unit = {
  val targs = tag.tpe match { case TypeRef(_, _, args) => args }
  println(s"type of $x has type arguments $targs")
}

与此相同:

import scala.reflect.runtime.universe._

def paramInfo[T: TypeTag](x: T): Unit = {
  val targs = typeOf[T] match { case TypeRef(_, _, args) => args }
  println(s"type of $x has type arguments $targs")
}

他们都给出了相同的结果:

scala> paramInfo(42)
type of 42 has type arguments List()

scala> paramInfo(List(1, 2))
type of List(1, 2) has type arguments List(Int)

除了带有上下文绑定的第二个版本比带有隐含参数的第一个版本稍微简单一点!