代码之家  ›  专栏  ›  技术社区  ›  Raphael Roth

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

  •  0
  • Raphael Roth  · 技术社区  · 8 年前

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

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

    这怎么写得好呢?

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

    因此,换句话说:如果a为None,b为None,则应返回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

    3 回复  |  直到 8 年前
        1
  •  2
  •   simpadjo    8 年前

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

        2
  •  0
  •   Raphael Roth    8 年前

    我自己刚刚找到了答案。还有一个 size 属性打开 Option (部分为1,无为0):

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

    为什么会这样?存在来自的隐式转换 Option[A] Iterable[A] 打电话 option2Iterable

        3
  •  -1
  •   Puneeth Reddy V    8 年前

    您可以尝试使用 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
    
    推荐文章