7

I am trying to create a Queue in Scala by doing:

import scala.collection.immutable.Queue

val empty = new Queue[Int]

However I am getting an error stating that the Queue constructor is protected. If this is the case, am I missing something? All the Queue methods seem to be defined and working. Must I really extend the Queue class for no reason just to use a Queue?

3 Answers 3

15

For empty Queue use companion object:

val empty = Queue.empty[Int]
Sign up to request clarification or add additional context in comments.

5 Comments

Ahh thanks. Hopefully this answer will come up above the articles saying to use new in google..
or Queue[Int](). If the context of the expression (more precisely, the Expected Type) makes it clear to the compiler that you're after a collection of Ints , you can omit the type parameter, e.g. val x: Queue[Int] = Queue().
@retronym It is using Queue[Int]() that was not working due to protected constructor. Using Scala 2.9.1.final.
@providence retronym is saying to use the companion object, val empty = Queue[Int]()
@Matthew Farwell Oh, sorry. I see that now.
3

Use one of the factories:

scala.collection.immutable.Queue()
scala.collection.immutable.Queue.empty

Note that immutable queues are co-variant, so you usually don't need to define a type for it. One exception would be var declarations.

Comments

0
scala> val empty = Queue [Int]()
empty: scala.collection.immutable.Queue[Int] = Queue()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.