为什么BitSet需要将显式强制转换视为Set [Int]的实例?

时间:2012-03-13 21:04:31

标签: scala scala-collections

在scaladoc中,BitSet被定义为扩展Set[Int]。所以我认为使用BitSet,因为Set[Int]的实例可行,但我的类型不匹配:

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()
                               ^

然而演员阵容有效:

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

那么为什么我需要明确地将BitSet转换为Set[Int],而Set[Int]Set[Int]的超类型?

1 个答案:

答案 0 :(得分:9)

事实证明,Set实际上是scala.collection.immutable.Set。所以你可以

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()

但不是

中的任何一个
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()

并且结果是Set的默认导入为您提供了x2。导入collection.immutable.BitSet或导入collection.Set(以涵盖collection.immutable.Set)。