【问题标题】:In scala reflection, how to resolve concrete type member?在scala反射中,如何解决具体类型成员?
【发布时间】:2020-01-10 19:12:44
【问题描述】:

我有一个程序在执行时可以产生一个抽象的 TypeTag:

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
}

执行结果为:

TypeTag[TypeResolving.this.example.T]

由于在这种情况下 example.T 已经定义,我还想获取实际的 TypeTag:

TypeTag[Map[String,Int]]

我怎么去那里?

【问题讨论】:

    标签: scala type-erasure scala-reflect


    【解决方案1】:

    试试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 来自这里)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-17
      • 2021-12-07
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多