Scala Guard function

 237 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala Guard function/statement in detail

Scala Guard function

Guard function/statement is simply a boolean expression.

Guard function/statement is mainly used for adding a boolean condition(guard function) in the ‘for loop comprehensions’ itself to filter/match the values.

Guard function/statement is a filter condition applied in for loop comprehensions or case statements. By using this, iteration becomes efficient as we are applying a filter to iteration and number iteration will be reduced.

Let us now see a few examples.

Below example is the usual way of filtering the elements in for loop. This is not efficient as we are touching or iterating over each element of the collection to match the filter.

object StaticReference {

  def main(args: Array[String]) {

    for (i <- 1 to 10) {
      if (i == 2) { Filtering only 2
        println(i)
      }
    }
  }
}

Output

2

If you see the above example, we are iterating each element and filtering only the element which is 2 and printing it.

This can be implemented efficiently by adding a guard function to the for loop comprehension.

object StaticReference {

  def main(args: Array[String]) {

    for (i <- 1 to 10 if i == 2) {
      println(i)
    }
  }
}

This seems more efficient as we have filtered out the data before itself.

Some more Scala guard function examples.

Filter even numbers using Guard function

object StaticReference {

  def main(args: Array[String]) {

    for (i <- 1 to 10 if i % 2 == 0) {
      println(i)
    }
  }
}

Output

2
4
6
8
10

Filter odd numbers using Guard function

object StaticReference {

  def main(args: Array[String]) {

    for (i <- 1 to 10 if i % 2 != 0) {
      println(i)
    }
  }
}

Output

1
3
5
7
9

Guard function/statement is very useful when adding a filter condition while iterating over a collection.

References: Official documentation

Please leave a comment and give us a thumbs up!.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.