如何在Scala中将Range转换为List或Array

Loi*_*oic 14 scala

我想将一系列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)
)
Run Code Online (Sandbox Code Playgroud)

我想知道是否有其他语法可能,为了避免使用foreach,我想在这部分代码中没有循环.

非常感谢!

卢瓦克

ten*_*shi 42

你可以使用toList方法:

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)
Run Code Online (Sandbox Code Playgroud)

toArray方法转换Range为数组.


Dan*_*ral 16

除了其他答案之外,还有这个:

List.range(firstYear, lastYear)
Run Code Online (Sandbox Code Playgroud)


she*_*lic 11

只是:

(1990 until 2011).toList
Run Code Online (Sandbox Code Playgroud)

但不要忘了,until包括最后一个数(2010年停止).如果您想要2011,请使用to:

(1990 to 2011).toList
Run Code Online (Sandbox Code Playgroud)


RoT*_*oRa 10

Range有一个toList和一个toArray方法:

firstYear.until(lastYear).toList

firstYear.until(lastYear).toArray
Run Code Online (Sandbox Code Playgroud)