scala

Initializing a scala BitSet from a range


I'd like to initialize a scala BitSet to contain the integers from 1 to N. The following will work, but I'm looking for a better solution:

var s = BitSet.empty ++ (1 to n)

I was hoping that I could do something like this:

var s:BitSet = (1 to n).toSet

...but that results in an error:

error: polymorphic expression cannot be instantiated to expected type;
  found   : [B >: Int]scala.collection.immutable.Set[B]
  required: scala.collection.immutable.BitSet

Am I missing something obvious?


Solution

  • Thats what breakOut is for:

    val s: BitSet = (1 to n).map(identity)(breakOut)
    

    See this question to understand the inner working of breakOut.

    Another solution is to use the constructor of BitSet:

    val s = BitSet((1 to n): _*)
    

    the : _* tells the compiler that you want to use the Range as repeated parameters.

    Because breakOut looks ugly you can use the pimp-my-library pattern to produce nicer looking code (as described here):

    val s = (1 to n).to[BitSet]