home search about rss feed twitter ko-fi

Ranges (Scala 3 Video)

Whenever you do these things, you’re using the Scala Range data type:

// Range in a `for` expression
val xs = for i <- 1 to 3 yield i * 10

// converting a Range to a List or Vector
(1 to 10).toList
(1 to 10).toVector

// other Ranges
1 to 5
0 to 10 by 2
0 to 100 by 10

Can use until as well as to:

(1 to 5).toList      // List(1, 2, 3, 4, 5)
(1 until 5).toList   // List(1, 2, 3, 4)

Can use Char values in ranges:

val r = ('a' to 'f').toList        // List(a, b, c, d, e, f)
val r = ('a' to 'f' by 2).toList   // List(a, c, e)

Infix methods

In uses like this, Range is used as a Scala infix method:

1 to 3

These two are equivalent:

1 to 3
1.to(3)

Laziness

Ranges are lazy:

val r = 1 to Int.MaxValue    // nothing happens right away

// these are all lazy
r.take(1)
r.drop(1)
r.distinct
r.tail

// this forces the action
r.filter(_ > 100)
r.map(_ * 2)

Update: All of my new videos are now on
LearnScala.dev