Using comparison operators in Scala's pattern matching system

后端 未结 4 571
忘掉有多难
忘掉有多难 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条回答
  •  旧时难觅i
    2020-12-07 11:45

    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.

提交回复
热议问题