Scala Ranges are a concise and efficient way to represent sequences of numbers. They are immutable collections that provide a convenient method for generating arithmetic progressions.
In Scala, you can create ranges using the to
and until
methods. The syntax is straightforward:
val inclusiveRange = 1 to 10
val exclusiveRange = 1 until 10
The to
method creates an inclusive range, while until
creates an exclusive range.
You can specify a step value to create ranges with custom increments:
val evenNumbers = 2 to 10 by 2
val descendingRange = 10 to 1 by -1
Ranges support various operations, including:
Here's an example demonstrating some range operations:
val r = 1 to 10
println(r.contains(5)) // true
println(r.start) // 1
println(r.end) // 10
println(r.step) // 1
val list = r.toList // Convert to List
Scala Ranges are memory-efficient, as they don't store all elements in memory. Instead, they calculate values on-demand, making them suitable for representing large sequences of numbers without consuming excessive memory.
Ranges integrate seamlessly with Scala's collection operations. You can use them with higher-order functions like map
, filter
, and fold
:
val squares = (1 to 5).map(x => x * x)
val evenSquares = squares.filter(_ % 2 == 0)
Scala Ranges offer a powerful and efficient way to work with sequences of numbers. Their integration with Scala's collection framework and lazy evaluation make them a valuable tool in many programming scenarios.
For more advanced usage, consider exploring Scala Collection Operations and Scala Lazy Evaluation.