title: Cast a variable to runtime type from existential typed TypeCast in Scala
body: <p><a href="https://stackoverflow.com/questions/29380839/trait-runtime-type-of-type-parameter-through-typetag-when-used-with-existential">This thread</a> addressed how to use <code>TypeTag</code> to get runtime type of type parameters when used with <code>Existential</code> type. <a href="https://stackoverflow.com/questions/29399090/how-to-cast-a-variable-to-certain-runtime-type-got-from-typecast-in-scala">Another thread</a> addressed how to cast a variable to its runtime type retrieved from <code>TypeTag</code>. </p>
  
  <p>My question builds on the aforementioned threads (kind of a combination of the two scenarios).  Parts of the code is duplicated from the two threads for clarity. </p>
  
  <pre><code>scala&gt; import scala.reflect.runtime.universe._
  import scala.reflect.runtime.universe._
  
  scala&gt; def cast[A](a: Any, tt: TypeTag[A]): A = a.asInstanceOf[A]
  cast: [A](a: Any, tt: reflect.runtime.universe.TypeTag[A])A
  
  scala&gt; abstract class Animal[T](implicit tt: TypeTag[T]) {
       |   val ttag = tt
       | }
  defined class Animal
  
  scala&gt; case object Dog extends Animal[Int]
  defined object Dog
  
  scala&gt; case object Cat extends Animal[String]
  defined object Cat
  
  scala&gt; val aa: List[(Animal[_], Any)] = List((Dog, 5), (Cat, "stringgg"), (Dog, 2))                                                                                                               
  aa: List[(Animal[_], Any)] = List((Dog,5), (Cat,stringgg), (Dog,2))
  
  scala&gt; aa(0)._1.ttag
  res25: reflect.runtime.universe.TypeTag[_] = TypeTag[Int]
  
  scala&gt; aa(1)._1.ttag
  res26: reflect.runtime.universe.TypeTag[_] = TypeTag[String]
  
  scala&gt; cast(aa(0)._2, aa(0)._1.ttag)
  res27: Any = 5
  
  scala&gt; cast(aa(1)._2, aa(1)._1.ttag)
  res28: Any = stringgg
  </code></pre>
  
  <p>In short, the last two lines: <code>cast(value, TypeTag[_])</code> always return a value of type <code>Any</code>. But my intention is to cast these values to the correct type stored in <code>Dog|Cat.ttag</code>, which, unfortunately, is not <code>TypeTag[Int]</code> or <code>TypeTag[String]</code> but <code>TypeTag[_]</code> due to usage of <code>existential</code> type. Is there any solution for it?</p>
  
  <p>Edit 1:</p>
  
  <p>Despite the field <code>ttag</code> is of type <code>TypeTag[_]</code>, <code>ttag.tpe</code> does have the right "type" (but as an instance of <code>reflect.runtime.universe.Type</code>). Is it possible to use the <code>typetag.tpe</code> to cast to the right type?</p>