Can a range be matched in Scala?

Justin Poliey picture Justin Poliey · Aug 28, 2009 · Viewed 22.4k times · Source

Is it possible to match a range of values in Scala?

For example:

val t = 5
val m = t match {
    0 until 10 => true
    _ => false
}

m would be true if t was between 0 and 10, but false otherwise. This little bit doesn't work of course, but is there any way to achieve something like it?

Answer

Alexander Azarov picture Alexander Azarov · Aug 28, 2009

Guard using Range:

val m = t match {
  case x if 0 until 10 contains x => true
  case _ => false
}