加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

有没有办法在Scala反射中将两个等效类型转换为两个相同的类型?

发布时间:2020-12-16 18:11:48 所属栏目:安全 来源:网络整理
导读:考虑以下: scala import scala.reflect.runtime.universe._import scala.reflect.runtime.universe._scala typeOf[Boolean]res23: reflect.runtime.universe.Type = Booleanscala typeOf[scala.Boolean]res24: reflect.runtime.universe.Type = Booleanscal
考虑以下:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> typeOf[Boolean]
res23: reflect.runtime.universe.Type = Boolean

scala> typeOf[scala.Boolean]
res24: reflect.runtime.universe.Type = Boolean

scala> res23 == res24
res25: Boolean = true

scala> typeOf[java.lang.Boolean]
res26: reflect.runtime.universe.Type = Boolean

scala> res23 == res26
res27: Boolean = false

scala> class Foo { def bf(arg: Boolean) = ??? }
defined class Foo

scala> typeOf[Foo]
res28: reflect.runtime.universe.Type = Foo

scala> res28.member(newTermName("bf")).asMethod
res30: reflect.runtime.universe.MethodSymbol = method bf

scala> res30.paramss.head.head
res31: reflect.runtime.universe.Symbol = value arg

scala> res31.typeSignature
res32: reflect.runtime.universe.Type = scala.Boolean

scala> res32 == res23
res33: Boolean = false

scala> res32 =:= res23
res37: Boolean = true

因此,通过typeOf [Boolean]函数获得的类型等同于通过检查方法获得的类型,但它不相等.

有没有办法将两个等价类型转换为结果相等的某些规范表示?我希望能够将它们用于地图中的键.

编辑:

更清楚的是,我正在寻找的是(不是真正的repl会话):

scala>val tp1 = // some type
scala>val tp2 = // equivalent type obtained another way
scala>tp1 == tp2
res1: Boolean = false
scala>tp1 =:= tp2
res2: Boolean = true
scala>val ctp1 = tp1.canonical
scala>val ctp2 = tp2.canonical
scala>ctp1 == ctp2
res3: Boolean = true
scala>ctp1 =:= tp1
res4: Boolean = true
scala>ctp2 =:= tp2
res5: Boolean = true

因此,转换会保留等价.我还需要它来处理参数化类型.

解决方法

从 the documentation开始:

It’s important to note that == should not be used to compare types for
equality—== can’t check for type equality in the presence of type
aliases,while =:= can.

您当然可以将类型存储在列表中并使用(例如)以下内容来检查包含:

myTypes.exists(_ =:= someType)

例如,您将在2.10编译器源中看到此方法.当然,它不如地图或集合那么高效,但是你通常在集合中没有很多这样的东西.

如果您必须具有地图或集合的性能,则可以根据您的要求使用擦除(如另一个答案所示)或typeSymbol.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读