Using comparison operators in Scala's pattern matching system

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

    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.

提交回复
热议问题