2011-04-10 9 views
13

Quiero convertir un rango de Int en una Lista o una Matriz. tengo este código de trabajo en Scala 2.8:Cómo convertir Rango a Lista o Matriz en Scala

var years: List[Int] = List() 
val firstYear = 1990 
val lastYear = 2011 

firstYear.until(lastYear).foreach(
    e => years = years.:+(e) 
) 

Me gustaría saber si hay otra sintaxis posible, evitar el uso de foreach, me gustaría tener ningún bucle en esta parte del código.

¡Muchas gracias!

Loic

Respuesta

38

Usted puede utilizar toList método:

método
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 convierte a Range matriz.

+1

Gracias! Esto funciona para 'Iterator's también, que estaba buscando –

10

Range tiene un toList y un método toArray:

firstYear.until(lastYear).toList 

firstYear.until(lastYear).toArray 
+0

Perfecto, muchas gracias !! – Loic

10

Simplemente:

(1990 until 2011).toList 

pero no se olvide que until hace no incluyen el último número (se detiene en 2010). Si quieres 2011, utilice to:

(1990 to 2011).toList 
+0

Genial, muchas gracias por su respuesta! – Loic

14

Y también está presente, además de las otras respuestas:

List.range(firstYear, lastYear) 
Cuestiones relacionadas