joesan
joesan

Reputation: 15435

Understanding TypeTag in Scala

I have the following piece of code:

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]

    }

What is the equivalent of the hasType[Other: TypeTag] method when I do?:

typeOf[Other] =:= selfTypeTag.tpe

Is it the same thing like doing?:

typeOf[Other] =:= typeOf[Self]

The type seems to just be a reflective representation of the Type some Type.

Upvotes: 2

Views: 102

Answers (1)

joesan
joesan

Reputation: 15435

Ok, I guess I managed to figure this out. Taking hint from the Scala documentation on TypeTag's, this version:

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")
}

does the same as this one:

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")
}

They both give the same result:

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)

Except that the second version with the context bound is just a little bit less verbose than the first version with the implicit parameter!

Upvotes: 1

Related Questions