2

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?

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
  • Maybe check this one http://stackoverflow.com/questions/789250/scala-is-there-a-way-to-use-priorityqueue-like-i-would-in-java – rofrol Mar 26 '14 at 15:11

1 Answers1

2

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

serejja
  • 22,901
  • 6
  • 64
  • 72
  • Your code works fine for me. What message do you get? – serejja Mar 26 '14 at 15:26
  • Scala 2.10.2 + java 1.8.0 (Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)) – serejja Mar 26 '14 at 15:30
  • Ok it works now, but it is still not clear for me, what method takes `(MyTypeQueOrdering)`? Also constructor? – IProblemFactory Mar 26 '14 at 15:30
  • Yes, the ordering must be available at creation time and it is used to prioritize elements. I suppose it is declared implicit just for convenience so that if you have an ordering in scope you don't have to explicitly pass it. You could roughly imagine PriorityQueue like this as well: `class PriorityQueue[A](ord: Ordering[A])`. This way your first example would work without the first parentheses fine. – serejja Mar 26 '14 at 15:40
  • In my example `PriorityQueue[MyType]()` ran constructor without parameter, where parameter should be there! `MyTypeQueOrdering` should go as an constructor parameter right? – IProblemFactory Mar 26 '14 at 16:09
  • `MyTypeQueOrdering` IS a constructor parameter, but an implicit one. `()` stands for explicit parameters, and as there are 0 of them, the parentheses can be omitted – serejja Mar 26 '14 at 18:46