Scala | Ranges
Last Updated :
08 Apr, 2019
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:
object GFG
{
def main(args : Array[String])
{
val x = Range( 3 , 10 , 1 )
println(x)
println(x( 0 ))
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:
object GFG
{
def main(args : Array[String])
{
val x = Range( 0 , 10 , 2 )
val y = 0 until 10 by 2
println(x == y)
}
}
|
Here, by method performs the work of increment.
- The upper bound of the Range can be made inclusive.
Example:
object GFG
{
def main(args : Array[String])
{
val x = Range( 1 , 8 )
val y = x.inclusive
println(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:
object GFG
{
def main(args : Array[String])
{
val x = Range( 1 , 8 )
val y = x.inclusive
val z = 1 to 8
println(y == z)
}
}
|
Thus, both the methods here performs the same task.
Please Login to comment...