scala - 扩展泛型类型 - PriorityQueue

标签 scala generics priority-queue generic-programming

我不明白为什么我需要 () 以及 MyTypeQueOrdering 的去向。 这是 PriorityQueue 的 header ,可在 official github 上找到。 :

class PriorityQueue[A](implicit val ord: Ordering[A])

这是我的尝试(有效):

class MyType{

}

object MyTypeQueOrdering extends Ordering[MyType]{
    def compare (n1:MyType, n2:MyType) = -1
}

class MyTypeQue extends PriorityQueue[MyType]()(MyTypeQueOrdering){

}

...但我不明白为什么我需要 ()PriorityQueue[MyType]() 是否返回某些内容?

最佳答案

尝试将MyTypeQueOrdering设为隐式对象:

object Implicits {
  //implicit objects can't be top-level ones
  implicit object MyTypeQueOrdering extends Ordering[MyType] {
    def compare(n1: MyType, n2: MyType) = -1
  }
}

这样你就可以省略两个括号:

import Implicits._

class MyTypeQue extends PriorityQueue[MyType] { ... }

在示例中需要空括号的原因是 PriorityQueue[MyType](MyTypeQueOrdering) 会假设您尝试将排序作为构造函数参数传递。因此,这就是为什么您需要显式显示无参数实例化,然后传递排序

关于scala - 扩展泛型类型 - PriorityQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22665131/

相关文章:

严格收集与 View 的性能比较

java - 如何为泛型对实现 equals?

java - 如何在泛型类上测试 instanceof?

python-2.7 - 检查优先级队列中是否已存在某些内容 Python

scala - 类是抽象的;无法在凿子上实例化错误

scala - 如何在 Scala 中定义无参数构造函数

scala - 在 Play 中使用 ScalaTest 对 Controller 进行单元测试!框架

java - 为什么 try-catch 不解决未经检查的泛型转换中的警告?

java - PriorityQueue 是 FIFO 队列吗?

php - PHP 和 MySQL 的定时事件优先级队列