bsky
bsky

Reputation: 20222

Scala Queue import error

If I import scala.collection._ and create a queue:

import scala.collection._
var queue = new Queue[Component]();

I get the following error:

error: not found: type Queue

However, if I also add

 import scala.collection.mutable.Queue

The error will disappear.

Why is this happening? Shouldn't scala.collection._ contain scala.collection.mutable.Queue?

Upvotes: 0

Views: 181

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

After import scala.collection._ you can use mutable.Queue; you could write Queue if there was a scala.collection.Queue (or one of scala.Queue, java.lang.Queue, and scala.Predef.Queue, since all of their members are imported by default), but there isn't.

It should be easy to see why it works this way: otherwise, the compiler (or anyone reading your code) would have no idea where they should look for the type: do you want scala.collection.Queue, scala.collection.mutable.Queue, or scala.collection.some.subpackage.from.a.library.Queue?

Upvotes: 0

user3248346
user3248346

Reputation:

You have to know how the Scala collections library is structured. It splits collections based on whether they are mutable or immutable.

Queue lives in the scala.collection.mutable package and scala.collection.immutable package. You have to specify which one you want e.g.

scala> import scala.collection.mutable._
import scala.collection.mutable._

scala> var q = new Queue[Int]()
q: scala.collection.mutable.Queue[Int] = Queue()


scala> import scala.collection.immutable._
import scala.collection.immutable._

scala> var q = Queue[Int]()
q: scala.collection.immutable.Queue[Int] = Queue()

Upvotes: 2

Related Questions