Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Scala反射API从singleton类型获取底层常量类型_Scala_Reflection_Scala Macros_Scala Reflect - Fatal编程技术网

如何使用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
  }
}