Match multiple cases classes in scala

后端 未结 3 1340
离开以前
离开以前 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:36

    Looks like you don't care about the values of the String parameters, and want to treat B and C the same, so:

    def matcher(l: Foo): String = {
      l match {
        case A() => "A"
        case B(_) | C(_) => "B"
        case _ => "default"
      }
    }
    

    If you must, must, must extract the parameter and treat them in the same code block, you could:

    def matcher(l: Foo): String = {
      l match {
        case A() => "A"
        case bOrC @ (B(_) | C(_)) => {
          val s = bOrC.asInstanceOf[{def s: String}].s // ugly, ugly
          "B(" + s + ")"
        }
        case _ => "default"
      }
    }
    

    Though I feel it would be much cleaner to factor that out into a method:

    def doB(s: String) = { "B(" + s + ")" }
    
    def matcher(l: Foo): String = {
      l match {
        case A() => "A"
        case B(s) => doB(s)
        case C(s) => doB(s)
        case _ => "default"
      }
    }
    

提交回复
热议问题