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 2
r: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9) scala>val r = 1 to 10 by 3
r: 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
5
When creating a Range
, you can
also use until
instead of to
:
scala> for (i <- 1 until 5) println(i)
1
2
3
4
Discussion
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 toArray
x: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala>val x = 1 to 10 toList
x: 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).toList
x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala>val x = (1 to 10).toArray
x: 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 ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.