How to get underlying constant type from singleton type with Scala reflection API

不想你离开。 提交于 2021-02-10 18:32:49

问题


import scala.reflect.runtime.universe._

val a: 42 = 42
val t: Type = typeOf[a.type]
assert(getConstantType(t).get =:= typeOf[42])

def getConstantType(t: Type): Option[ConstantType] = ???

How could I generally implement getConstantType so that the above assertion passes? I assumed that something like this was possible since the assertion below passes:

assert(t <:< typeOf[42])

t.widen goes too far as it return Int. I'm looking for something that returns Int(42).


回答1:


How about

assert(t.resultType =:= typeOf[42])

Updated -

def getConstantType[T](t: T): t.type = t

Update 2 -

def getConstantType(tp: Type): Option[ConstantType] = {
  tp.erasure match {
    case ConstantType(_) => Some(tp.erasure.asInstanceOf[ConstantType])
    case _ => None
  }
}



回答2:


Try

def getConstantType(tp: Type): Option[ConstantType] = {
  def unrefine(t: Type): Type = t.dealias match {
    case RefinedType(List(t), scope) if scope.isEmpty => unrefine(t)
    case t                                            => t
  }

  unrefine(tp) match {
    case SingleType(_, sym) => sym.typeSignature match {
      case NullaryMethodType(t) => unrefine(t) match {
        case c: ConstantType => Some(c)
        case _               => None
      }
      case _                 => None
    }
    case _                   => None
  }
}


来源:https://stackoverflow.com/questions/59567310/how-to-get-underlying-constant-type-from-singleton-type-with-scala-reflection-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!