Scala Ranges
A Range is an ordered sequence of evenly spaced integers, such as 1 to 10 or 0 to 100 in steps of 5. Ranges are lazy and tiny: 1 to 1_000_000 stores only its start, end and step, not a million numbers. They are most often used in for loops, but they are full collections with all the usual methods.
to and until
@main def run(): Unit =
println((1 to 5).toList)
println((1 until 5).toList)
println((0 to 20 by 5).toList)
println((10 to 1 by -3).toList)
println((1 to 0).toList)List(1, 2, 3, 4, 5)
List(1, 2, 3, 4)
List(0, 5, 10, 15, 20)
List(10, 7, 4, 1)
List()
| Expression | Contains | Includes end? |
|---|---|---|
1 to 5 |
1, 2, 3, 4, 5 | yes |
1 until 5 |
1, 2, 3, 4 | no |
0 to 10 by 2 |
0, 2, 4, 6, 8, 10 | yes, if reached by the step |
5 to 1 by -1 |
5, 4, 3, 2, 1 | yes |
1 to 0 |
nothing | — |
Tip: Use
untilwith zero-based indexes:0 until xs.lengthvisits every valid index. Even better, usexs.indices, which gives you exactly that range.
Ranges are collections
@main def run(): Unit =
val r = 1 to 10
println(r.sum)
println(r.filter(_ % 3 == 0))
println(r.map(n => n * n).takeRight(3))
println(r.contains(7))
println(r.length)
println(r.reverse.take(3))
println(r)55
Vector(3, 6, 9)
Vector(64, 81, 100)
true
10
Range 10 to 8 by -1
Range 1 to 10
Methods that must create new elements, such as map and filter, return a Vector. Methods that can stay a range, such as reverse and take, return a Range.
Ranges in loops
@main def run(): Unit =
val word = "SCALA"
for i <- word.indices do
println(s"$i: ${word(i)}")
for row <- 1 to 3 do
println((1 to row).map(_ => "*").mkString)0: S
1: C
2: A
3: L
4: A
*
**
***
A multiplication table
Two nested ranges and a yield produce a small table without any mutable state.
@main def run(): Unit =
val n = 4
val rows =
for i <- 1 to n yield
(1 to n).map(j => f"${i * j}%3d").mkString
rows.foreach(println) 1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
Other numeric ranges
Long ranges work the same way. For decimal steps, use BigDecimal ranges, which avoid floating-point drift:
@main def run(): Unit =
println((1L to 3L).toList)
println((BigDecimal("0.0") to BigDecimal("1.0") by BigDecimal("0.25")).toList)
println(('a' to 'e').mkString)
println(('a' to 'z' by 5).toList)List(1, 2, 3)
List(0.0, 0.25, 0.50, 0.75, 1.00)
abcde
List(a, f, k, p, u, z)
Character ranges are handy for alphabets and labels.
Inclusive or exclusive? A summary
| You want… | Write |
|---|---|
| count from 1 to n | 1 to n |
| every index of a collection | xs.indices or 0 until xs.length |
| count down | n to 1 by -1 or (1 to n).reverse |
| every second number | 0 to n by 2 |
| a range of letters | 'a' to 'z' |
Test yourself
How many numbers are in 0 until 10?
- 9
- 10
- 11
- 0
What does (10 to 1 by -3).toList produce?
List(10, 7, 4, 1)List(1, 4, 7, 10)List()List(10, 7, 4)
What does (1 to 3).map(_ * 2) return?
Range(2, 4, 6)Vector(2, 4, 6)List(2, 4, 6)Array(2, 4, 6)