Scala模式匹配中的情况类实例,具有任意数量的None字段。

huangapple go评论52阅读模式
英文:

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?

huangapple
  • 本文由 发表于 2023年6月12日 22:56:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定