Using comparison operators in Scala's pattern matching system

Viewed 80104

Is it possible to match on a comparison using the pattern matching system in Scala? For example:

a match {
    case 10 => println("ten")
    case _ > 10 => println("greater than ten")
    case _ => println("less than ten")
}

The second case statement is illegal, but I would like to be able to specify "when a is greater than".

5 Answers

While all the above and bellow answers perfectly answer the original question, some additional information can be found in the documentation https://docs.scala-lang.org/tour/pattern-matching.html , they didn't fit in my case but because this stackoverflow answer is the first suggestion in Google I would like to post my answer which is a corner case of the question above.
My question is:

  • How to use a guard in match expression with an argument of a function?

Which can be paraphrased:

  • How to use an if statement in match expression with an argument of a function?

The answer is the code example below:

    def drop[A](l: List[A], n: Int): List[A] = l match {
      case Nil => sys.error("drop on empty list")
      case xs if n <= 0 => xs
      case _ :: xs => drop(xs, n-1)
    }

link to scala fiddle : https://scalafiddle.io/sf/G37THif/2 as you can see the case xs if n <= 0 => xs statement is able to use n(argument of a function) with the guard(if) statement.

I hope this helps someone like me.

Scala's pattern matching allows you to define your own extractor. In this case, you can simply define a new extractor:

class GreaterThan(n: Int) {
  def unapply(i: Int) = i > n
}

val GreaterThan10 = GreaterThan(10)

a match {
  case 10 => ???
  case GreaterThan10() => ???
  case _ => ???
}

or just use pattern guards.

Related