Creating a Range of Numbers
Explore how to create numeric ranges in Scala collections. Understand using to for inclusive ranges, by for specifying intervals between numbers, and until for exclusive upper limits. This lesson helps you efficiently generate ordered sequences of integers for use in Scala programming.
We'll cover the following...
Introduction
In the previous lessons, we used the range method to populate a collection. A Range is also a collection in itself. It is an ordered sequence of integers with the integers being equally spread apart from one another by an equal interval.
Creating a Range Using to
We can create a Range by fixing to between the lower limit and upper limit of a Range.
The code snippet above creates a range of numbers starting from 1 all the way up to 10.
Specifying an Interval Using by
We can specify the interval between each element using by.
The code snippet above creates a range of numbers starting from 1 all the way to 10 with an interval of 2 between two numbers. In other words, this would give us all the odd integers from 1 to 10.
Creating a Range Using until
When we want to exclude the upper limit in a Range, we can use until fixed between the lower limit and the excluded upper limit.
The code snippet above creates a range of numbers starting from 1 until 3. In other words, it’s a range of numbers starting from 1 and ending at 2.
In the next lesson, we will discuss Streams; the last collection covered in this course.