How can I pattern match on a range in Scala?

Theo picture Theo · Jul 1, 2010 · Viewed 11.8k times · Source

In Ruby I can write this:

case n
when 0...5  then "less than five"
when 5...10 then "less than ten"
else "a lot"
end

How do I do this in Scala?

Edit: preferably I'd like to do it more elegantly than using if.

Answer

Yardena picture Yardena · Jul 1, 2010

Inside pattern match it can be expressed with guards:

n match {
  case it if 0 until 5 contains it  => "less than five"
  case it if 5 until 10 contains it => "less than ten"
  case _ => "a lot"
}