Scala Ranges

In this tutorial, we will learn about the Scala ranges with examples. By Shivang Yadav Last updated : April 02, 2023

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,

1) By using "to" keyword

Syntax : 
var range_name = a to b 

Example: 
var a = 3 to 6 // gives 3 , 4, 5, 6.

2) 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.

3) By using "range" keyword

Syntax : 
var range_name = range(a,b,x) 

Example: 
var a = range(3,6,1)// gives 3 , 4, 5,6.

Initialization of range with data structure

The range can also be directly initialized to a data structure like an array, list, vector, map. Methods to initialize range to an array:

Using '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.

Example: Scala program to demonstrate the use of 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




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.