Does Scala have guards?

Solution 1:

Yes, it uses the keyword if. From the Case Classes section of A Tour of Scala, near the bottom:

def isIdentityFun(term: Term): Boolean = term match {
  case Fun(x, Var(y)) if x == y => true
  case _ => false
}

(This isn't mentioned on the Pattern Matching page, maybe because the Tour is such a quick overview.)


In Haskell, otherwise is actually just a variable bound to True. So it doesn't add any power to the concept of pattern matching. You can get it just by repeating your initial pattern without the guard:

// if this is your guarded match
  case Fun(x, Var(y)) if x == y => true
// and this is your 'otherwise' match
  case Fun(x, Var(y)) if true => false
// you could just write this:
  case Fun(x, Var(y)) => false

Solution 2:

Yes, there are pattern guards. They're used like this:

def boundedInt(min:Int, max: Int): Int => Int = {
  case n if n>max => max
  case n if n<min => min
  case n => n
}

Note that instead of an otherwise-clause, you simply specifiy the pattern without a guard.