如何使用Scala反射API从singleton类型获取底层常量类型
我通常如何实现如何使用Scala反射API从singleton类型获取底层常量类型,scala,reflection,scala-macros,scala-reflect,Scala,Reflection,Scala Macros,Scala Reflect,我通常如何实现getConstantType,从而通过上述断言? 我假设这样的事情是可能的,因为下面的断言通过了: 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] = ??? 断言
getConstantType
,从而通过上述断言?
我假设这样的事情是可能的,因为下面的断言通过了:
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] = ???
断言(t
assert(t <:< typeOf[42])
更新-
assert(t.resultType =:= typeOf[42])
更新2-
def getConstantType[T](t: T): t.type = t
试一试
这确实通过了断言,但对于我的用例,我需要从
t
获取ConstantType
,因此我确实在寻找getConstantType
的实现。为getConstantType更新更新了更新的getConstantType
方法不会按需要返回类型ConstantType
的值。
def getConstantType(tp: Type): Option[ConstantType] = {
tp.erasure match {
case ConstantType(_) => Some(tp.erasure.asInstanceOf[ConstantType])
case _ => None
}
}
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
}
}