Using comparison operators in Scala's pattern matching system Ask Question

Using comparison operators in Scala's pattern matching system Ask Question

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".

ベストアンサー1

You can add a guard, i.e. an if and a boolean expression after the pattern:

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

Edit: Note that this is more than superficially different to putting an if after the =>, because a pattern won't match if the guard is not true.

おすすめ記事