scalapattern-matchingcase-class

Scala pattern match case class instance with arbitrary number of None fields


Let's say I have the following snippet of Scala

case class A(a: Option[String], b: Option[String])
val v: A = A(None, None)
val vOp: Option[A] = v match {
  case A(None, None) => None  // can I make this simpler / more generalized
  ...
}

Is there a way for me to pattern match when an instance of A contains all None values without explicitly typing out each one?

e.g. I'm looking for something along the lines of case A(None :_*) => None, but I know that's not syntactically valid.

Context My use case is that I am pattern matching a case class with many underlying fields that changes frequently so I'd like to avoid needing to enumerate all the potential None values if possible.


Solution

  • Well, you could do something like this:

    object Empty {
       def unapply(p: Product) = p.productIterator.forall(_ == None)
    }
    

    Then you can write:

       A(None, None) match { 
         case Empty() => "is empty"
         case _ => "not empty"
       }
    

    But for the record, I don't think this is a very good idea. You say you need this, because there are many fields, and they change often. But then the "base case", when everything is None is the least of your problems. When some fields are not None, what are you going to do? What usefu logic can your match statement possibly have, if you don't know what fields are there, not even just how many fields there are?