Why does BitSet require an explicit cast to be considered an instance of Set [Int]?

In scaladoc, BitSet is defined as an extension of Set[Int] . Therefore, I thought that using BitSet , as in the case 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, casting works:

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

So, why should I explicitly highlight BitSet in Set[Int] , and Set[Int] is the supertype of Set[Int] ?

+6
source share
1 answer

Turns out 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 close collection.immutable.Set ).

+9
source

Source: https://habr.com/ru/post/910636/


All Articles