Return Boolean With If-Else in Scala

This article will teach us how to return Boolean values when working with if-else in Scala.

Return Boolean With if-else in Scala

Let’s see a scenario to understand it better.

def check(): Boolean = {
    for ((digit1,digit2,digit3) <- digitsSet){
      if ((1,5,6) == (digit1,digit2,digit3))
        true
      else
        false
    }
  }

val digitsSet = Set((10,20,30),(1,5,6),(78,109,23),(14,25,57))

In the above code, we are trying to find whether our set contains those three digits, so we expect either true or false as the output, but when the above code is executed, we get the following error.

type mismatch;
 found   : Unit
 required: Boolean
    for ((digit1,digit2,digit3) <- digitsSet){

The problem is that the function should return Boolean instead of Unit.

So we can solve this problem in different ways.

  1. Using the contains method to find an element in our set. It returns true if the element is present; else returns false.

    This is a more elegant way of writing the above code.

    Example code:

    val digitsSet = Set((10,20,30),(1,5,6),(78,109,23),(14,25,57))
    println(digitsSet.contains((10,20,30)))
    

    Output:

    true
    
  2. Adding a return statement before true and false. This is the best way as it is versatile and can be used in almost any scenario.

```scala
val digitsSet = Set((10,20,30),(1,5,6),(78,109,23),(14,25,57))

def check(): Boolean = {
    val store = for ((digit1,digit2,digit3) <- digitsSet) {
      if ((10,20,30) == (digit1,digit2,digit3))
        return true
    }
    false
  }

println(check())
```

Output:

```text
true
```
  1. Using the exists method in Scala.

    val digitsSet = Set((10,20,30),(1,5,6),(78,109,23),(14,25,57))
    
    println(digitsSet.exists( _ == (1,20,50) ))
    

    Output:

    false
    
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.