Learn How To Use Range

By Nadim Bahadoor | Last updated: July 25, 2017 at 13:36 pm

Overview

In this tutorial, we will show how to use the Scala Range to help you easily write many items such as numbers or characters in sequence that can be used in looping constructs.

 Steps

1. Create a simple numeric range from 1 to 5 inclusive

This simple example should be familiar to you since we have used it in the previous For Comprehension tutorial. To create a range of integers starting with 1, incrementally adding 1 up to and including the number 5, you can do the following:


println("Step 1: Create a simple numeric range from 1 to 5 inclusive")
val from1To5 = 1 to 5
println(s"Range from 1 to 5 inclusive = $from1To5")

You should see the following output when you run your Scala application in IntelliJ:


Step 1: Create a simple numeric range from 1 to 5 inclusive
Range from 1 to 5 inclusive = Range(1, 2, 3, 4, 5)

NOTE:

  • We are using the to keyword which means that the number 5 was included.

2. Create a numeric range from 1 to 5 but excluding the last integer number 5

Let's extend the example from Step 1 and create a range of integers starting with 1 and incrementally adding 1 up to the last upper bound of number of 5:


println("\nStep 2: Create a numeric range from 1 to 5 but excluding the last integer number 5")
val from1Until5 = 1 until 5
println(s"Range from 1 until 5 where 5 is excluded = $from1Until5")

You should see the following output when you run your Scala application in IntelliJ:


Step 2: Create a numeric range from 1 to 5 but excluding the last integer number 5
Range from 1 until 5 where 5 is excluded = Range(1, 2, 3, 4)

NOTE:

  • We are using the until keyword to exclude the last upper bound which is number 5.

3. Create a numeric range from 0 to 10 but increment with multiples of 2

In the examples from Step 1 and 2, we incremented the next number in the range by the default value of 1. But, what if you wanted to increment the range by some arbitrary number other that 1.


println("\nStep 3: Create a numeric range from 0 to 10 but increment with multiples of 2")
val from0To10By2 = 0 to 10 by 2
println(s"Range from 0 to 10 with multiples of 2 = $from0To10By2")

You should see the following output when you run your Scala application in IntelliJ:


Step 3: Create a numeric range from 0 to 10 but increment with multiples of 2
Range from 0 to 10 with multiples of 2 = Range(0, 2, 4, 6, 8, 10)

NOTE:

  • We are using the by keyword to increment by the number 2 as opposed to the default value of 1.

4. Create an alphabetical range to represent letter a to z
So far we have shown how to create numerical ranges. What if you wanted to print the English alphabet starting from the letter a to the letter z.


println("\nStep 4: Create an alphabetical range to represent letter a to z")
val alphabetRangeFromAToZ = 'a' to 'z'
println(s"Range of alphabets from a to z = $alphabetRangeFromAToZ")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: Create an alphabetical range to represent letter a to z
Range of alphabets from a to z = NumericRange(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)

NOTE:

  • We are using single quotes and not double quotes such that we end up with a character range.

5. Character ranges with user specified increment

What if you had to print every alternate character in the English alphabet. Similar to Step 3, this can be achieved using the by keyword.


println(s"\nStep 5: Character ranges with user specified increment")
val alphabetRangeFromAToZBy2 = 'a' to 'z' by 2
println(s"Range of every other alphabet = $alphabetRangeFromAToZBy2")

You should see the following output when you run your Scala application in IntelliJ:


Step 5: Character ranges with user specified increment
Range of every other alphabet = NumericRange(a, c, e, g, i, k, m, o, q, s, u, w, y)

6. Convert the Scala Range into collections
If you recall from the previous For Comprehension tutorial, we made use of range inside the for loop construct. What if you wanted to store a range in some data structure such as List, Set, Sequence or an Array.


  println("\nStep 6: Storing our ranges into collections")
  val listFrom1To5 = (1 to 5).toList
  println(s"Range to list = ${listFrom1To5.mkString(" ")}")

  val setFrom1To5 = (1 to 5).toSet
  println(s"Range to set = ${setFrom1To5.mkString(" ")}")

  val sequenceFrom1To5 = (1 to 5).toSeq
  println(s"Range to sequence = ${sequenceFrom1To5.mkString(" ")}")

  val arrayFrom1To5 = (1 to 5).toArray
  println(s"Range to array = `${arrayFrom1To5.mkString(" ")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 6: Storing our ranges into collections
Range to list = 1 2 3 4 5
Range to set = 5 1 2 3 4
Range to sequence = 1 2 3 4 5
Range to array = `1 2 3 4 5

NOTE:

  • We are calling the .toList, .toSet and .toSeq functions to convert our ranges into List, Set and Sequence accordingly.
  • Note also we skipped the () when calling the conversion functions and instead used .toList as opposed to .toList() This may be confusing at first if you are coming from say Java or .NET! But I hope it will become more clear when we get to tutorials on functions. The general practice is to skip the () if the function has no side effects.
  • We are also calling the .mkString() function to create a string representation of each collection type. The .mkString() function takes in a delimiter which in our case is just an empty space.

This concludes our tutorial on Learn How To Use Range and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to create an inclusive range of integers
  • How to create a range of integers which excludes the upper bound
  • How to create an integer range with a different increment by parameter
  • How to create an alphabet character range from a to z
  • How to create an alphabet character range from a to z with a different increment by parameter
  • How to convert our ranges into collection data structures such as List, Set and Sequence.

Tip

  • In Step 6, we showed how to convert our ranges into collections such as List, Set, Sequence and Array. We then used the mkString() function to create a string representation for the elements in the collection. However, to access and print each element in the collection, you could just as easily used the foreach() function.

arrayFrom1To5.foreach(print(_))

The key thing to remember here is that we used the wildcard _ as part of the print() function parameter.

 

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will continue on looping constructs and go over using the while loop in Scala.

 

Stay tuned!

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Senior Software Developer | Elsevier
Founder of allaboutscala.com. I have over 10 years of experience in building large scale real-time trading systems in the financial industry. Passionate about Distributed Systems, Scala, Big Data and Functional Programming. Stay in touch for upcoming tutorials!
Other allaboutscala.com tutorials you may like:

Share this article on