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

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

    How about this:

        Welcome to Scala version 2.8.0.r20327-b20091230020149 (Java HotSpot(TM) Client VM, Java 1.6.0_17).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> def m(v1: Any,v2: Any) = (v1,v2) match {
         |     case (Some(x),Some(y)) => "a"
         |     case (Some(_),None) | (None,Some(_)) => "b"
         |     case _ => "c"
         | }
    m: (v1: Any,v2: Any)java.lang.String
    
    scala> m(Some(1),Some(2))
    res0: java.lang.String = a
    
    scala> m(Some(1),None)
    res1: java.lang.String = b
    
    scala> m(None,None)
    res2: java.lang.String = c
    
    scala>
    

提交回复
热议问题