我不明白为什么我需要()
,因此MyTypeQueOrdering
去哪里。这是PriorityQueue
的标题,在官方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
和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)
会假设您试图将排序作为构造函数参数传递。这就是为什么需要显式显示无参数实例化然后传递排序