Scala Ranges

A Range is a sequence of numbers generated on demand between a start and end value. Instead of building a List with hundreds of numbers, a Range stores only the start, end, and step — it generates each value when needed. Ranges are memory-efficient and work naturally with all Scala collection operations.

Creating Ranges

val inclusive  = 1 to 10       // 1, 2, 3, ..., 10 (includes 10)
val exclusive  = 1 until 10    // 1, 2, 3, ..., 9  (excludes 10)
val withStep   = 0 to 20 by 5  // 0, 5, 10, 15, 20
val countdown  = 10 to 1 by -1 // 10, 9, 8, ..., 1
val charRange  = 'a' to 'z'    // a, b, c, ..., z

Range in Loops

for i <- 1 to 5 do print(s"$i ")
// 1 2 3 4 5

for i <- 0 until 10 by 2 do print(s"$i ")
// 0 2 4 6 8

for ch <- 'A' to 'E' do print(ch)
// ABCDE

Range Operations

val r = 1 to 100

r.sum          // 5050
r.min          // 1
r.max          // 100
r.length       // 100
r.contains(50) // true
r.toList       // List(1, 2, ..., 100)
r.toArray      // Array(1, 2, ..., 100)
r.filter(_ % 7 == 0)  // all multiples of 7: Vector(7, 14, 21, ...)
r.map(_ * _ )          // squares: Vector(1, 4, 9, ...)

Memory Efficiency


// A Range stores only 3 values:
val bigRange = 1 to 1000000000   // 1 billion numbers
// Only stores: start=1, end=1000000000, step=1
// Memory: ~constant

// Converting to List materializes all values:
// val bigList = bigRange.toList   // would use ~4GB RAM — avoid!

println(bigRange.sum)    // 500000000500000000L  — computed lazily
println(bigRange.last)   // 1000000000           — computed instantly

Ranges as Indices

val items = List("a", "b", "c", "d", "e")

// Access elements by range index
for i <- 0 until items.length do
  println(s"$i: ${items(i)}")

// Pythonic: use indices directly
items.indices.foreach(i => println(s"$i: ${items(i)}"))

Practical Examples

// Times table
val n = 7
(1 to 10).foreach(i => println(f"$n × $i = ${n * i}%2d"))

// Sum of even numbers from 1 to 100
val evenSum = (2 to 100 by 2).sum
println(s"Sum of evens: $evenSum")   // 2550

// Check prime (simple)
def isPrime(n: Int): Boolean =
  n > 1 && (2 to math.sqrt(n).toInt).forall(n % _ != 0)

val primes = (2 to 50).filter(isPrime)
println(primes.mkString(", "))
// 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47

Leave a Comment

Your email address will not be published. Required fields are marked *