Question

I wanted to have a Queue class that could be used the same way as a list.

For instance,

val q = Queue()

would instantiate an empty queue.

For that purpose I tried using a companion class :

object Queue {
    def apply() = new Queue[Any]
}

Is that the right way to do it ?

Was it helpful?

Solution

Using the apply method of the companion object is the right way to do it, but you could also add a type parameter on apply itself:

object Queue {
    def apply[T]() = new Queue[T]
}

So that you can create a Queue of the right type:

val q = Queue[Int]()

Usually you also allow populating the sequence on creation, so that the element type can be inferred, as in:

def apply[T](elms: T*) = ???

So that you can do:

val q = Queue(1,2,3) // q is a Queue[Int]

OTHER TIPS

Yes.

If you want to initialise an object without using new, then using apply() as a factory method in the companion is absolutely the right way to go about it.

You might also want to consider a more specific factory (or factories) to help make your code more self-documenting.

object Queue {
  def apply[T](xs: T*) = new Queue(xs: _*)
  def empty[T] = new Queue[T]()
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top