如何使用 Scala 反射 API 从单例类型获取底层常量类型 [英] How to get underlying constant type from singleton type with Scala reflection API

查看:67
本文介绍了如何使用 Scala 反射 API 从单例类型获取底层常量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 以使上述断言通过?我认为这样的事情是可能的,因为下面的断言通过了:

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 太过分了,因为它返回 Int.我正在寻找返回 Int(42) 的东西.

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

推荐答案

尝试

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
  }
}

这篇关于如何使用 Scala 反射 API 从单例类型获取底层常量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆