【问题标题】:Extend generic type - PriorityQueue扩展泛型类型 - PriorityQueue
【发布时间】:2014-03-26 15:07:46
【问题描述】:

我不明白为什么我需要() 以及MyTypeQueOrdering 的去向。 这是PriorityQueue 的标头,在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]() 会返回什么吗?

【问题讨论】:

标签: scala generics priority-queue generic-programming


【解决方案1】:

尝试将MyTypeQueOrdering 设为implicit object

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 2.10.2 + java 1.8.0(Java HotSpot(TM) 64-Bit Server VM(build 25.0-b70,混合模式))
  • 好的,现在可以了,但是我还是不太清楚,(MyTypeQueOrdering)采用什么方法?也是构造函数?
  • 是的,排序必须在创建时可用,并且用于确定元素的优先级。我想它被声明为隐式只是为了方便,这样如果你在范围内有一个排序,你就不必显式地传递它。您也可以大致想象 PriorityQueue 是这样的:class PriorityQueue[A](ord: Ordering[A])。这样,您的第一个示例可以在没有第一个括号的情况下正常工作。
  • 在我的例子中PriorityQueue[MyType]() 运行了没有参数的构造函数,参数应该在那里! MyTypeQueOrdering 应该作为构造函数参数吧?
猜你喜欢
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多