16

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

4 Answers 4

46

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This works for Iterators too, which I was looking for
20

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

List.range(firstYear, lastYear)

Comments

12

Range has a toList and a toArray method:

firstYear.until(lastYear).toList

firstYear.until(lastYear).toArray

Comments

12

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.