如何检查scala中是否定义了两个选项/未定义

问题描述 投票:0回答:3

我想检查两个选项的“状态”是否相同:

val a : Option[Double]= ??
val b : Option[Double]= ??

怎么能以一种好的方式写出来呢?

val sameState = (a.isDefined && b.isDefined) || (!a.isDefined && !b.isDefined)

所以在单词中:如果a是None而b是Non,它应该返回true,如果a是Some而b是Some,它也应该返回true,否则它应该返回false

我的解决方案似乎相当不容乐观。我正在寻找类似的东西:

val sameState = (a.definition == b.definition)

编辑:背景:

我有一个Seq[Option[_]],并希望将它分成一个Seq[Seq[Option[_]]取决于连续元素的“状态”是否像Grouping list items by comparing them with their neighbors一样变化

scala
3个回答
2
投票

也许只是a.isDefined == b.isDefined


0
投票

我自己找到了答案。在size上还有一个Option属性(对于Some为1,对于None为0):

val sameState = (a.size == b.size)

为什么会这样?有一个从Option[A]Iterable[A]的隐式转换,称为option2Iterable


-1
投票

您可以尝试使用match而不是您拥有的两个选项的元组。像这样的东西

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"
}

产量

isBothDefined(Option.apply(1.0), Option.empty[Double])
res3: String = b is not defined
© www.soinside.com 2019 - 2024. All rights reserved.