开发者

How to convert Range to List or Array in Scala

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 c开发者_高级运维ode.

Thanks a lot!

Loic


You can use toList method:

scala> 1990 until 2011 toList
res2: List[Int] = List(1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010)

toArray method converts Range to array.


And there's also this, in addition to the other answers:

List.range(firstYear, lastYear)


Range has a toList and a toArray method:

firstYear.until(lastYear).toList

firstYear.until(lastYear).toArray


Simply:

(1990 until 2011).toList

but don't forget that until does not include the last number (stops at 2010). If you want 2011, use to:

(1990 to 2011).toList
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜