How to Return Boolean With If-Else in Scala

Suraj P Feb 02, 2024 Scala Scala Boolean
How to 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:

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

Output:

```text
true
```
  1. 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.

    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
    
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Suraj P
Suraj P avatar Suraj P avatar

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

LinkedIn GitHub