Using comparison operators in Scala's pattern matching system

后端 未结 4 569
忘掉有多难
忘掉有多难 2020-12-07 11:02

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

a match {
    case 10 => println(\"ten\")
    case _ >         


        
4条回答
  •  臣服心动
    2020-12-07 11:30

    A solution that in my opinion is much more readable than adding guards:

    (n compare 10).signum match {
        case -1 => "less than ten"
        case  0 => "ten"
        case  1 => "greater than ten"
    }
    

    Notes:

    • Ordered.compare returns a negative integer if this is less than that, positive if greater, and 0 if equal.
    • Int.signum compresses the output from compare to -1 for a negative number (less than 10), 1 for positive (greater than 10), or 0 for zero (equal to 10).

提交回复
热议问题