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

比较Scala中的类型

发布时间:2020-12-16 09:52:58 所属栏目:安全 来源:网络整理
导读:我有两个对象,每个对象都有本地定义的类型,我想确定类型是否相同.例如,我想要编译这段代码: trait Bar { type MyType}object Bar { def compareTypes(left: Bar,right: Bar): Boolean = (left.MyType == right.MyType)} 但是,编译失败,“值MyType不是Bar的
我有两个对象,每个对象都有本地定义的类型,我想确定类型是否相同.例如,我想要编译这段代码:

trait Bar {
  type MyType
}

object Bar {
  def compareTypes(left: Bar,right: Bar): Boolean = (left.MyType == right.MyType)
}

但是,编译失败,“值MyType不是Bar的成员”.

这是怎么回事?有没有办法做到这一点?

解决方法

你可以做到这一点,但它需要一些额外的机制:

trait Bar {
  type MyType
}

object Bar {
  def compareTypes[L <: Bar,R <: Bar](left: L,right: R)(
    implicit ev: L#MyType =:= R#MyType = null
  ) = ev != null
}

现在,如果我们有以下内容:

val intBar1 = new Bar { type MyType = Int }
val intBar2 = new Bar { type MyType = Int }
val strBar1 = new Bar { type MyType = String }

它按预期工作:

scala> Bar.compareTypes(intBar1,strBar1)
res0: Boolean = false

scala> Bar.compareTypes(intBar1,intBar2)
res1: Boolean = true

诀窍是要求L#MyType和R#MyType相同的隐含证据,并提供默认值(null),如果它们不相同.然后,您可以检查是否获得默认值.

(编辑:李大同)

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

    推荐文章
      热点阅读