Scala - Range Operator



In Scala, there are two operators that are used to create sequences of numbers (ranges). The range operators are i.e., ranges can be created using "to" and "until".

Range Operators (to and unitl)

Operator Description Example
to Creates a range inclusive of both ends 1 to 5 creates a range from 1 to 5
until Creates a range excluding the upper bound 1 until 5 creates a range from 1 to 4

Syntax

The Syntax of the range operators −

// Using 'to' to create an inclusive range from start to end
val range1 = start to end

// Using 'until' to create a range from start to (end - 1)
val range2 = start until end

The 'to' method in Scala creates a range that includes both the start and end values. It generates a sequence where each integer value from start to end is included. For example: 1 to 5 creates a range from 1 to 5. Hence resulting in the sequence (1, 2, 3, 4, 5).

The 'until' method creates a range that includes the start value but excludes the end value. It generates a sequence where each integer value from start up to, but not including, end is included. For example: 1 until 5 creates a range from 1 to 4. Hence resulting in the sequence (1, 2, 3, 4).

Try the following example program to understand all Range operators available in Scala Programming Language.

Example of Scala Range Operators (to and until)

object Demo {
   def main(args: Array[String]) = {
      // Using 'to' to create an inclusive range from 1 to 5
      val range1 = 1 to 5
      println("Range 1: " + range1.toList) // Output: Range 1: List(1, 2, 3, 4, 5)
      
      // Using 'until' to create a range from 1 to 4 (exclusive)
      val range2 = 1 until 5
      println("Range 2: " + range2.toList) // Output: Range 2: List(1, 2, 3, 4)
   }
}

The range1 is assigned the range 1 to 5. This includes integers from 1 to 5 inclusive. The .toList method converts this range to a list for printing.

The range2 is assigned the range 1 until 5. This includes integers from 1 to 4. The .toList method converts this range to a list for printing.

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Range 1: List(1, 2, 3, 4, 5)
Range 2: List(1, 2, 3, 4)

These operators (to and until) are basic for creating ranges of integers in Scala. These are useful for iterating over sequences and defining boundaries in various programming scenarios.

Advertisements