[英]How to check whether two Options are both defined / undefined in scala
I want to check whether the "state" of two options are the same: 我想检查两个选项的“状态”是否相同:
val a : Option[Double]= ??
val b : Option[Double]= ??
How can this be written in a nice way? 如何用一种不错的方式写出来?
val sameState = (a.isDefined && b.isDefined) || (!a.isDefined && !b.isDefined)
So in words : If a is None and b is None it shoud return true, if a is Some and b is Some it should also return true, otherwise it should return false 换句话来说:如果a为None且b为None,则应该返回true,如果a为Some且b为Some,则也应返回true,否则应返回false
My solution seems quite unscala-ish. 我的解决方案似乎很烂。 I'm looing for something like:
我正在寻找类似的东西:
val sameState = (a.definition == b.definition)
Edit : background: 编辑:背景:
I have a Seq[Option[_]]
and want to split it into a Seq[Seq[Option[_]]
depending on whether the "state" of consecutive elements changes as in Grouping list items by comparing them with their neighbors 我有一个
Seq[Option[_]]
,想将连续元素的“状态”是否像在分组列表项中那样通过将它们与它们的邻居进行比较来将其拆分为一个Seq[Seq[Option[_]]
也许只是a.isDefined == b.isDefined
吗?
Just found an answer myself. 我自己才找到答案。 There is also a
size
attribute on Option
(being 1 for Some, 0 for None): Option
上还有一个size
属性(对于Some,为1,对于None,为0):
val sameState = (a.size == b.size)
Why this works? 为什么这样有效? There is an implicit conversion from
Option[A]
to Iterable[A]
called option2Iterable
从
Option[A]
到Iterable[A]
的隐式转换称为option2Iterable
You can try using match
over the tuple of two option you are having. 您可以尝试对两个选项的元组使用
match
。 Something like this 像这样
def isBothDefined(a : Option[Double], b : Option[Double]) = (a,b) match{
case (Some(x), Some(y)) => "Both defined"
case (Some(x), None) => "b is not defined"
case (None, Some(y)) => "a is not defined"
case _ => "nither s defined"
}
Output 产量
isBothDefined(Option.apply(1.0), Option.empty[Double])
res3: String = b is not defined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.