Match multiple cases classes in scala

后端 未结 3 1346
离开以前
离开以前 2021-01-30 04:47

I\'m doing matching against some case classes and would like to handle two of the cases in the same way. Something like this:

abstract class Foo
case class A ext         


        
3条回答
  •  花落未央
    2021-01-30 05:24

    Well, it doesn't really make sense, does it? B and C are mutually exclusive, so either sb or sc get bound, but you don't know which, so you'd need further selection logic to decide which to use (given that they were bound to a Option[String], not a String). So there's nothing gained over this:

      l match {
        case A() => "A"
        case B(sb) => "B(" + sb + ")"
        case C(sc) => "C(" + sc + ")"
        case _ => "default"
      }
    

    Or this:

      l match {
        case A() => "A"
        case _: B => "B"
        case _: C => "C"
        case _ => "default"
      }
    

提交回复
热议问题