Home »
Scala language
Ranges in Scala
Scala Range: A range is a set of numbers with a specific interval. In Scala, ranges are used to define a number sequence and can increase code efficiency. In this Scala ranges tutorial, we will learn about ranges in Scala.
Submitted by Shivang Yadav, on July 22, 2019
Scala Range
A Range is a bounded series with a uniform interval with an upper and lower limit. The range literal is a numerical sequence of number ranging with a certain limit.
This defined sequence has many uses in programming like in easy initialization of the loop, sequence problems, etc.
Methods to initialize a range
There are multiple methods by which a range variable can be initialized. They are,
-
By using "to" keyword
Syntax : var range_name = a to b
Example: var a = 3 to 6 // gives 3 , 4, 5, 6.
-
By using "by" keyword with others: Increases the interval
Syntax : var range_name = a until b by x
Example: var a = 3 until 10 by 2 // gives 3, 5, 7, 9.
-
By using "range" keyword
Syntax : var range_name = range(a,b,x)
Example: var a = range(3,6,1)// gives 3 , 4, 5,6.
The range can also be directly initialized to a data structure like an array, list, vector, map. Methods to initialize range to an array:
toarray Method
var var_name = (2 to 6 ).toarray
Using range method of array object
var var_name = Array.range(5 to 9)
In a similar way List and vector method works.
Sample code to illustrate use of Scala range
object myObject
{
def rangeprint(a:Range){
println(a)
println(a(1))
println(a.last)
}
def main(args: Array[String])
{
val R1 = 3 to 6
val R2 = 3 until 7
var R3 = 3 to 11 by 2
var R4 = Range(3,45,4)
rangeprint(R1)
rangeprint(R2)
rangeprint(R3)
rangeprint(R4)
}
}
Output
Range 3 to 6
4
6
Range 3 until 7
4
6
Range 3 to 11 by 2
5
11
inexact Range 3 until 45 by 4
7
43