从范围初始化 scala BitSet [英] Initializing a scala BitSet from a range

查看:42
本文介绍了从范围初始化 scala BitSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想初始化一个 scala BitSet 以包含从 1 到 N 的整数.以下方法可行,但我正在寻找更好的解决方案:

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?

推荐答案

这就是 breakOut 的用途:

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

请参阅这个问题以了解breakOut的内部工作原理.

See this question to understand the inner working of breakOut.

另一种解决方案是使用BitSet的构造函数:

Another solution is to use the constructor of BitSet:

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

: _* 告诉编译器你想使用 Range 作为重复参数.

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

因为 breakOut 看起来很丑,你可以使用 pimp-my-library 模式来生成更好看的代码(如 此处):

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]

这篇关于从范围初始化 scala BitSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆