Search code examples
scalatype-erasurescala-reflect

In scala reflection, how to resolve concrete type member?


I have a program that can yield an abstract TypeTag when executed:

class TypeResolving extends FunSpec {

  import org.apache.spark.sql.catalyst.ScalaReflection.universe._

  val example = new Example

  it("can convert") {

    val t1 = implicitly[TypeTag[example.T]]
    println(t1)
  }
}

object TypeResolving {

  class Example {

    type T = Map[String, Int]
  }
  val example = new Example
}

The execution results in:

TypeTag[TypeResolving.this.example.T]

Since in this case example.T is already defined, I would also like to get the actual TypeTag:

TypeTag[Map[String,Int]]

How do I get there?


Solution

  • Try dealias

    def dealias[T, T1](typeTag: TypeTag[T]): TypeTag[T1] = backward(typeTag.tpe.dealias)
    
    val typeTag = implicitly[TypeTag[TypeResolving.example.T]] //TypeTag[TypeResolving.example.T]
    val typeTag1 = dealias(typeTag) //TypeTag[scala.collection.immutable.Map[String,Int]]
    
    val typeTag2 = implicitly[TypeTag[Map[String, Int]]] //TypeTag[Map[String,Int]]
    val typeTag3 = dealias(typeTag2) //TypeTag[scala.collection.immutable.Map[String,Int]]
    
    typeTag1 == typeTag3 //true
    

    How to get the aliased type of a type alias in scala runtime?

    Get a TypeTag from a Type? (backward is from here)