Search code examples
scalagenericspriority-queuegeneric-programming

Extend generic type - PriorityQueue


I can't understand why I need () and hence where MyTypeQueOrdering goes. Here is header of PriorityQueue, found on official github:

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

Here is my try (which works):

class MyType{

}

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

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

}

... but I can't figure out why I need (). Does PriorityQueue[MyType]() return something?


Solution

  • Try making MyTypeQueOrdering an 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
      }
    }
    

    This way you can omit both parentheses:

    import Implicits._
    
    class MyTypeQue extends PriorityQueue[MyType] { ... }
    

    The reason you need the empty parentheses in your example is because PriorityQueue[MyType](MyTypeQueOrdering) would assume you're trying to pass the ordering as a constructor parameter. So that's why you need to explicitly show no-arg instantiation and then passing the ordering