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

前端 未结 6 1802
野趣味
野趣味 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:12

    Since you already matched against (Some(x), Some(y)), you may match against (None, None) explicitly, and the remaining cases are (Some(x), None) and (None, Some(y)):

    def decide [T](v1: Option[T], v2:Option[T]) = (v1, v2) match {
      case (Some (x), Some (y)) => "a"
      case (None, None)         => "c"
      case _                    => "b"
    }
    
    val ni : Option [Int] = None 
    decide (ni, ni)            // c
    decide (Some (4), Some(3)) // a
    decide (ni, Some (3))      // b
    decide (Some (4), ni)      // b
    

提交回复
热议问题