BitSet to set [Int] or vice versa in Scala

I have a library that uses BitSet, and I need to change data like Set [Int] to use the library.

What comes to mind is to use operations .toSeq:_*, but I'm not sure if this is an efficient way to convert from BitSet to Set [Int] or vice versa.

scala> BitSet(Set(1,2,3).toSeq:_*)
res55: scala.collection.immutable.BitSet = BitSet(1, 2, 3)

scala> Set(BitSet(1,2,3).toSeq:_*)
res56: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

Is there a better way?

+4
source share
2 answers

The Scala Sethierarchy is a little strange, but in this case it BitSetis Set[Int]like a super-type, so you can just pass it to a BitSetmethod that expects Set[Int], etc.

, , Set, , immutable.Set ( scala.collection), , BitSet scala.collection, immutable.BitSet. , immutable, , .

immutable Set, BitSet, BitSet to Set :

scala> import scala.collection.immutable.BitSet
import scala.collection.immutable.BitSet

scala> val bs = BitSet(0, 100, 200)
bs: scala.collection.immutable.BitSet = BitSet(0, 100, 200)

scala> def takesSet(s: Set[Int]): Int = s.size
takesSet: (s: Set[Int])Int

scala> takesSet(bs)
res0: Int = 3

scala.collection.BitSet, toSet:

scala> takesSet(scala.collection.BitSet(0, 100, 200).toSet)
res1: Int = 3

:

scala> val s = Set(1, 2, 3)
s: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> BitSet(s.toSeq: _*)
res2: scala.collection.immutable.BitSet = BitSet(1, 2, 3)

, CanBuildFrom:

scala> val bs: BitSet = Set("1", "2", "3").map(_.toInt)(collection.breakOut)
bs: scala.collection.immutable.BitSet = BitSet(1, 2, 3)

, :

scala> val bs: BitSet = BitSet(Set("1", "2", "3").map(_.toInt).toSeq: _*)
bs: scala.collection.immutable.BitSet = BitSet(1, 2, 3)

( ) BitSet collection.breakOut , CanBuildFrom, BitSet , CanBuildFrom map, : flatMap, scanLeft, ++ , .

+5

-: BitSet Set[Int], , :

     import scala.collection._
     val set: Set[Int] = BitSet(1,2,3)

:

     val bs: BitSet = BitSet(set.toStream:_*)

, " ", 99% , : Set , , .

0

All Articles