How to create a TypeTag manually?

前端 未结 4 1552
悲&欢浪女
悲&欢浪女 2020-11-28 13:43

I\'m interested in creating a TypeTag manually (since 2.10M5):

object X {
  import reflect.runtime.universe._
  def tt[A : TypeTag](a: A) = typeTag[A] // how         


        
4条回答
  •  失恋的感觉
    2020-11-28 14:15

    The function definition

    def tt[A : TypeTag](a: A) = typeTag[A]
    

    is just another way of writing

    def tt(a: A)(implicit tag: TypeTag[A]) = tag
    

    which means that the instance of a tag is being created implicitly by the compiler. The reasoning behind this is that Scala compiler solves the JVM's type erasure problem by hardcoding the otherwise erased type information.

    In case you're not familiar with type erasure issue, it is that JVM doesn't store the type parameters information, for instance a type Seq[Set[Int]] would be seen simply as Seq[_] by the JVM and there would be no way for you to find out the missing type information with reflection.

提交回复
热议问题