Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Range to List or Array in Scala

Tags:

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 code.

Thanks a lot!

Loic

like image 200
Loic Avatar asked Apr 10 '11 15:04

Loic


1 Answers

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.

like image 138
tenshi Avatar answered Oct 15 '22 21:10

tenshi