2.8. Creating a Range, List, or Array of Numbers
Problem
You need to create a range, list, or array of numbers, such as in
a for loop, or for testing
purposes.
Solution
Use the to method of the
Int class to create a Range with the desired elements:
scala> val r = 1 to 10
r: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5,
6, 7, 8, 9, 10)You can set the step with the by method:
scala>val r = 1 to 10 by 2r: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9) scala>val r = 1 to 10 by 3r: scala.collection.immutable.Range = Range(1, 4, 7, 10)
Ranges are commonly used in for
loops:
scala> for (i <- 1 to 5) println(i)
1
2
3
4
5When creating a Range, you can
also use until instead of to:
scala> for (i <- 1 until 5) println(i)
1
2
3
4Discussion
Scala makes it easy to create a range of numbers. The first three
examples shown in the Solution create a Range. You can easily convert a Range to other sequences, such as an Array or List, like this:
scala>val x = 1 to 10 toArrayx: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala>val x = 1 to 10 toListx: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Although this infix notation syntax is clear
in many situations (such as for
loops), it’s generally preferable to use this syntax:
scala>val x = (1 to 10).toListx: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala>val x = (1 to 10).toArrayx: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
The magic that makes this process work is the to and until methods, which you’ll ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access