Using comparison operators in Scala's pattern matching system

后端 未结 4 558
忘掉有多难
忘掉有多难 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:39

    As a non-answer to the question's spirit, which asked how to incorporate predicates into a match clause, in this case the predicate can be factored out before the match:

    def assess(n: Int) {
      println(
        n compare 10 match {
          case 0 => "ten"
          case 1 => "greater than ten"
          case -1 => "less than ten"
        })
    }
    

    Now, the documentation for scala.math.Ordering.compare(T, T) promises only that the non-equal outcomes will be greater than or less than zero. Java's Comparable#compareTo(T) is specified similarly to Scala's. It happens to be conventional to use 1 and -1 for the positive and negative values, respectively, as Scala's current implementation does, but one can't make such an assumption without some risk of the implementation changing out from underneath.

提交回复
热议问题