Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
理解Scala中的TypeTag_Scala_Types - Fatal编程技术网

理解Scala中的TypeTag

理解Scala中的TypeTag,scala,types,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.

我有以下代码:

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]

该类型似乎只是
类型的反射表示
某些
类型
好吧,我想我已经设法解决了这个问题。根据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)
除了具有上下文绑定的第二个版本比具有隐式参数的第一个版本稍微详细一点之外