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

scala – 使用仅针对兼容类型编译的抽象类型定义特征的排序?

发布时间:2020-12-16 10:01:43 所属栏目:安全 来源:网络整理
导读:假设以下特征: trait A { type B } 是否有任何方法可以将其转换为有序类型,其中只能比较具有相同B的A,并且这是在编译时强制执行的? 解决方法 是的,通过隐式(使用类型别名使事情变得更加干燥), type AA[T] = A { type B = T }implicit def aIsOrdered[T](a
假设以下特征:

trait A {
  type B       
}

是否有任何方法可以将其转换为有序类型,其中只能比较具有相同B的A,并且这是在编译时强制执行的?

解决方法

是的,通过隐式(使用类型别名使事情变得更加干燥),

type AA[T] = A { type B = T }

implicit def aIsOrdered[T](a : AA[T]) = new Ordered[AA[T]] {
  def compare(that : AA[T]) = 0
}

示例REPL会话,

scala> val ai1 = new A { type B = Int }
ai1: java.lang.Object with A{type B = Int} = $anon$1@1ec264c

scala> val ai2 = new A { type B = Int }
ai2: java.lang.Object with A{type B = Int} = $anon$1@1a8fb1b

scala> val ad = new A { type B = Double }
ad: java.lang.Object with A{type B = Double} = $anon$1@891a0

scala> ai1 < ai2
res2: Boolean = false

scala> ai1 < ad
<console>:16: error: type mismatch;
 found   : ad.type (with underlying type java.lang.Object with A{type B = Double})
 required: AA[Int]
       ai1 < ad
             ^

编辑…

由于scala.math.LowPriorityOrderingImplicits中的隐式定义,这个定义足以为我们提供相应的Ordering类型类实例.这允许我们将A用于需要排序的类型,例如.一个scala.collection.SortedSet,

scala> implicitly[Ordering[AA[Int]]]
res0: Ordering[AA[Int]] = scala.math.LowPriorityOrderingImplicits$$anon$4@39cc63

scala> import scala.collection.SortedSet
import scala.collection.SortedSet

scala> val s = SortedSet(ai1,ai2)
s: scala.collection.SortedSet[java.lang.Object with A{type B = Int}] = TreeSet($anon$1@1a8fb1b)

(编辑:李大同)

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

    推荐文章
      热点阅读