6

In the scaladoc, BitSet is defined as extending Set[Int]. So I thought using a BitSet as in instance of Set[Int] would work, but I get a type mismatch:

Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_29).

scala> import collection.BitSet
import collection.BitSet

scala> val b: Set[Int] = BitSet()
<console>:8: error: type mismatch;
 found   : scala.collection.BitSet
 required: Set[Int]
       val b: Set[Int] = BitSet()
                               ^

However a cast works:

scala> val b: Set[Int] = BitSet().asInstanceOf[Set[Int]]
b: Set[Int] = BitSet()

So why do I need to explicitely cast a BitSet to a Set[Int] while Set[Int] is a super-type of Set[Int]?

Julien Gaugaz
  • 321
  • 3
  • 10

1 Answers1

9

It turns out that your Set is actually scala.collection.immutable.Set. So you can

val b0: Set[Int] = collection.immutable.BitSet()
val b1: collection.Set[Int] = collection.BitSet()
val b2: collection.immutable.Set[Int] = collection.immutable.BitSet()
val b3: collection.mutable.Set[Int] = collection.mutable.BitSet()
val b4: collection.Set[Int] = collection.immutable.BitSet()
val b5: collection.Set[Int] = collection.mutable.BitSet()

but not any of

val x1: collection.immutable.Set[Int] = collection.BitSet()
val x2: collection.immutable.Set[Int] = collection.mutable.BitSet()
val x3: collection.mutable.Set[Int] = collection.BitSet()
val x4: collection.mutable.Set[Int] = collection.immutable.BitSet()

and it turns out that the default import for Set gives you x2. Import collection.immutable.BitSet, or import collection.Set (to cover collection.immutable.Set).

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • @jullybobble - You're still confused. `collection.Set` and `scala.collection.Set` are _exactly the same thing_. You mean `Set` from `Predef`. – Rex Kerr Mar 13 '12 at 21:36
  • Note: I removed my first comment on which @Rex answered because it was wrong and misleading. – Julien Gaugaz Mar 14 '12 at 07:29