Scala | Ranges
The Range in Scala can be defined as an organized series of uniformly separated Integers. It is helpful in supplying more strength with less methods so, operations performed here are very quick.
Some important points:
- The Ranges can be utilized by the for loops for iteration.
- It can be obtained using some predefined methods namely until, by, and to.
- It is defined by three constants i.e, (start, end, and increment value).
Syntax:
val range = Range(x, y, z)
Where, x is the lower limit, y is the upper limit, and z is the increment.
Example:
// Scala program for Ranges // Creating objectobject GFG{ // Main method def main(args: Array[String]) { // applying range method val x = Range(3, 10, 1) // Displays given range println(x) // Displays starting value // of the given range println(x(0)) // Displays last value // of the given range println(x.last) }} |
Output:
Range(3, 4, 5, 6, 7, 8, 9) 3 9
Thus, we can say that upper bound of the Range is not inclusive.
Operations performed on Ranges
- If we want a range inclusive of the end value, we can also use the until method both until and Range methods are used for the same purpose.
Example:// Scala program for Ranges// Creating objectobjectGFG{// Main methoddefmain(args:Array[String]){// applying range methodvalx=Range(0,10,2)// applying until methodvaly=0until10by2// Displays true if both the// methods are equivalentprintln(x==y)}}Output:true
Here, by method performs the work of increment.
- The upper bound of the Range can be made inclusive.
Example:// Scala program for Ranges// Creating objectobjectGFG{// Main methoddefmain(args:Array[String]){// applying range methodvalx=Range(1,8)// Including upper boundvaly=x.inclusive// Displays all the elements// of the rangeprintln(y)}}Output:Range(1, 2, 3, 4, 5, 6, 7, 8)
Here, inclusive is used to include upper bound of the Range.
- If we want a range of integer values, we can use the to method both to and inclusive Ranges are equivalent.
Example:// Scala program for Ranges// Creating objectobjectGFG{// Main methoddefmain(args:Array[String]){// applying range methodvalx=Range(1,8)// Including upper boundvaly=x.inclusive// applying 'to' methodvalz=1to8// Displays true if both the// methods are equalprintln(y==z)}}Output:true
Thus, both the methods here performs the same task.



