Search code examples
listscalainstantiationtypeclassempty-list

Best way to instantiate a type parameter class in Scala


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 ?


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]