SCAla loops

 

This time we will look at how you can use the various loops within Scala

 

For Loops

The for loop in Scala is quite handy, and does some things that other languages do not provide within their for loop symantics

Range

The simplest for of a for loop is as shown here

//simple range for loop
var a = 0
for(a <- 1 to 10) {
    println(s"Value of a = $a")
}

Which would give the following results

image

You can also use until instead of to, which would give you the same results

Collections

You can also use a for loop to loop through a collection

//simple for loop through a collection
var list = List(1,2,3,4)
var a = 0
for(a <- list) {
  println(s"Value of a = $a")
}

Which would give the following results

image

 

Using Filters

Filters may also be applied to for loops, here is an example

//simple for loop through a collection
//with a filter for only even numbers
var list = List(1,2,3,4)
var a = 0
for(a <- list if a % 2 ==0) {
  println(s"Value of a = $a")
}

Which when run gives the following results

image

Using Yield

You can also create to new sequences (if you are a .NET programmer which is really who this posts are aimed at, this would be the same as using a LINQ Select to create a new IEnumerable for some source IEnumerable)

//simple for loop through a collection
//with a filter for only even numbers
//which use yield to create filtered sequence
var list = List(1,2,3,4)
var a = 0
var evens = for {a <- list if a % 2 ==0
            } yield a

for(a <- evens) {
  println(s"Value of a = $a")
}

Which when run produces the following results

image

 

While Loops

Much the same as other languages, Scala has a while loop that allows us to continue looping while waiting for a certain condition to be met. It is important to note that the while loop checks the condition at the top of the loop, so if the condition is already met the while loop may never run

//simple while loop
var a = 0
while(a < 10) {
  println(s"Value of a = $a")
  a = a + 1
}

Which when run will give the following result

image

 

Do While Loops

Scala also has the popular do-while loop, which unlike the while loop will check the condition at the end of the do-while, so is guaranteed to run at least once. Here is a simple example

//simple do-while loop
var a = 0
do {
  println(s"Value of a = $a")
  a = a + 1
}while(a < 10)
//import control packages to give us Breaks
import scala.util.control._

//simple breakable for loop
val loop = new Breaks()
var a = 0
loop.breakable {
  for(a <- 0 to 20) {
    println(s"Value of a = $a")
    if(a > 5)
      loop.break()
  }
}
println("Outisde the loop")

Which when run will give you the following results

image

 

Breaking Out Of Loops

This is one key area where Scala is very different from .NET. There is no built in break statement available.

However if you are using a version of Scala after 2.8 then there is a way to use a break statement inside your loops.

You need to import a package to allow this to happen.

The idea is that you wrap your loop in a breakable which is available by using the Breaks class. And then inside your loop when some condition occurs your may use Breaks classes break() method

Lets see an example

//import control packages to give us Breaks
import scala.util.control._

//simple breakable for loop
val loop = new Breaks()
var a = 0
loop.breakable {
  for(a <- 0 to 20) {
    println(s"Value of a = $a")
    if(a > 5)
      loop.break()
  }
}
println("Outisde the loop")

Which when run gives the following results

image

Advertisements

4 thoughts on “SCAla loops

  1. abatishchev says:

    I always was under impression that your code should not have loops. And especially your FP code. Isn’t it always better to map/bind?

  2. sachabarber says:

    The way I see it is Scala is a general purpose language, and yes you do have functional constructs available like map, flatmap etc etc, but it also supports loops. This series of posts is more for people from .NET land too, so they would not be used to not using loops at all, though if they are really good with LINQ and RX who knows

  3. sachabarber says:

    By the way I found a really nice Async-Await Scala library, and RX library for Scala so I am happy

  4. elifarley says:

    You’re not mutating the list in your example, so you don’t really need to give up on immutability when declaring ‘list’. So instead of using the keyword ‘var’, you could have used ‘val’:

    //simple for loop through a collection
    val list = List(1,2,3,4)
    var a = 0
    for(a <- list) {
    println(s"Value of a = $a")
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: