views:

242

answers:

2

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?

+5  A: 

You can use guards:

val m = t match {
    case x if (0 <= x && x < 10) => true
    case _ => false
}
Alexey Romanov
+13  A: 

Guard using Range:

val m = t match {
  case x if 0 until 10 contains x => true
  case _ => false
}
Alexander Azarov
That's very clever! For some reason, I never thought of doing it that way...
Daniel Spiewak