在Scala中简化Option [Boolean]表达式 [英] Simplifying Option[Boolean] expression in Scala

查看:63
本文介绍了在Scala中简化Option [Boolean]表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

optionBoolean.getOrElse(false) && otherOptionBoolean.getOrElse(false)

Scalastyle告诉我可以简化它.怎么样?

And Scalastyle tells me that it can be simplified. How?

推荐答案

您可以尝试以下操作:

Seq(optionBoolean, otherOptionBoolean).forall(_.contains(true))

在Scala 2.13中(与先前版本非常相似), forall 方法位于

In Scala 2.13 (it is very similar in prior versions) the forall method is located at IterableOnce, and its implementation is:

def forall(p: A => Boolean): Boolean = {
  var res = true
  val it = iterator
  while (res && it.hasNext) res = p(it.next())
  res
}

因此,一旦有一个不满足条件的值,循环就会中断,其余的将不会被测试.

Therefore once there is a value that doesn't satisfy the condition, the loop will break, and the rest will not be tested.

代码在 Scastie .

这篇关于在Scala中简化Option [Boolean]表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆