Alex Rivera | Logout

Can a range be matched in Scala?

Asked 2009-08-28T10:18:30.700
54

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?

Edit
Report

2 Answers

82

Guard using Range:

val m = t match {
  case x if 0 until 10 contains x => true
  case _ => false
}
answered 2009-08-28T10:48:17.893
3

Here's another way to match using a range:

val m = t match {
  case x if ((0 to 10).contains(x)) => true
  case _ => false
}
answered 2012-07-02T04:28:36.210

Your Answer