如何在 Scala 中将 Range 转换为列表或数组
我想将一系列 Int 转换为 List 或 Array。 我有这段代码在 Scala 2.8 中工作:
var years: List[Int] = List()
val firstYear = 1990
val lastYear = 2011
firstYear.until(lastYear).foreach(
e => years = years.:+(e)
)
我想知道是否有其他可能的语法,以避免使用 foreach,我希望在这部分代码中没有循环。
多谢!
卢伊克
I want to convert a range of Int into a a List or an Array.
I have this code working in Scala 2.8:
var years: List[Int] = List()
val firstYear = 1990
val lastYear = 2011
firstYear.until(lastYear).foreach(
e => years = years.:+(e)
)
I would like to know if there is another syntax possible, to avoid using foreach, I would like to have no loop in this part of code.
Thanks a lot!
Loic
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
toList
方法:toArray
方法将Range
转换为数组。You can use
toList
method:toArray
method convertsRange
to array.除了其他答案之外,还有这个:
And there's also this, in addition to the other answers:
Range
有一个toList
和一个toArray
方法:Range
has atoList
and atoArray
method:简单地说:
但不要忘记
until
不包含最后一个数字(截至 2010 年)。如果您想要 2011 年,请使用to
:Simply:
but don't forget that
until
does not include the last number (stops at 2010). If you want 2011, useto
: