Scala: Pattern matching when one of two items meets some condition

前端 未结 6 1706
野趣味
野趣味 2021-02-20 12:53

I\'m often writing code that compares two objects and produces a value based on whether they are the same, or different, based on how they are different.

So I might writ

6条回答
  •  独厮守ぢ
    2021-02-20 13:13

    You should be able to do it if you define it as a val first:

    val MyValThatIsCapitalized = new OneAndOnlyOne(v: Option[Foo] => v.isDefined )
    val result = (v1,v2) match {
      case (Some(value1), Some(value2)) => "a"
      case MyValThatIsCapitalized(value) => "b"
      case _ = > "c"
    }
    

    As implied by the name, the name of the val containing the extractor object must be capitalized.

提交回复
热议问题