英文:
Scala pattern match case class instance with arbitrary number of None fields
问题
有没有办法在实例A
包含全部None
值时进行模式匹配,而不需要明确列出每个值?
例如,我正在寻找类似于case A(None :_*) => None
的东西,但我知道那不是语法上有效的。
背景
我的使用案例是,我正在模式匹配一个具有许多基础字段的案例类,这些字段经常更改,因此如果可能的话,我希望避免需要列出所有潜在的None
值。
英文:
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.
答案1
得分: 4
你可以像这样做:
object Empty {
def unapply(p: Product) = p.productIterator.forall(_ == None)
}
然后你可以编写:
A(None, None) match {
case Empty() => "为空"
case _ => "不为空"
}
但就记录而言,我认为这不是一个很好的主意。你说你需要这个,因为有很多字段,它们经常更改。但当一些字段不是`None`时,你将怎么办?如果你不知道有哪些字段,甚至不知道有多少字段,你的`match`语句可能有什么有用的逻辑呢?
英文:
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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论