Manu Chadha
Manu Chadha

Reputation: 16729

Is there a way to use match with boolean

I find using match more readable than if. If I have a boolean value, can I use it with match?

I usually do

if(!authorised) {...} else {..}

But I am unable to do

authorised match {
    case ??? //what here??
}

Upvotes: 0

Views: 4286

Answers (5)

Andronicus
Andronicus

Reputation: 26026

You can simply write:

authorised match {
  case true => ...
  case false => ...
}

Although intellij suggests refactoring to if statement.

Upvotes: 3

francoisr
francoisr

Reputation: 4585

You can do this using

authorised match {
    case true => ...
    case false => ...
}

Note that pattern matching on boolean values is not very idiomatic in Scala, and you'd probably be better off using the standard if/else expression. The compiler will actually not manage to generate the same efficient code for the pattern match, as discussed in this answer. It's very common for Scala beginners to get over-enthusiastic with pattern matching and start using it everywhere, but in the case of plain booleans, it really makes sense to stick with if/else.


Side-note: Other answers have mentioned using a default clause like

authorised match {
   case true => /*true case*/
   case false => /*false case*/
   case _ => /* default case */
}

This is unnecessary, as Boolean can only ever be true or false. Like all primitive types, they cannot be assigned null so the additional clause is useless and the compiler will justifiably warn you about it.

warning: unreachable code
       case _ => /* default case */

Upvotes: 2

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

You just need to use boolean literals:

authorised match {
   case true => /*true case*/
   case false => /*false case*/
}

Upvotes: 5

Mario Galic
Mario Galic

Reputation: 48400

Alternatively to pattern match, consider mouse which provides extension methods for booleans, for example, consider fold

authorised.fold("It is true", "It is false")

Upvotes: 3

Teena Vashist
Teena Vashist

Reputation: 111

You can do like this:

authorised match {
  case true => // true case 
  case false => // false case
  case _ => // other case for exception or null
}

Upvotes: 0

Related Questions