I have code like that:
optionBoolean.getOrElse(false) && otherOptionBoolean.getOrElse(false)
And Scalastyle tells me that it can be simplified. How?
When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. There are a few methods that we can Call on Scala Option.
Scala isEmpty () Method If the Scala Option is None, this returns true; otherwise, it returns false. scala> a.isEmpty res2: Boolean = false scala> b.isEmpty res3: Boolean = true Learn: Scala Arrays and Multidimensional Arrays in Scala
One place we get an Option value is through the get () method for a Map. Here, it returns Some (1) when it finds the key “Megha” in the Map (where 1 is the value for that key).
Simplification Using K-map K-map uses some rules for the simplification of Boolean expressions by combining together adjacent cells into single term. The rules are described below − Rule 1 − Any cell containing a zero cannot be grouped.
You can try the following:
Seq(optionBoolean, otherOptionBoolean).forall(_.contains(true))
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.
Code run at Scastie.
This is perhaps a bit clearer:
optionBoolean.contains(true) && otherOptionBoolean.contains(true)
Just to throw another, not-necessarily-better answer on the pile,
optionBoolean == Some(true) && otherOptionBoolean == Some(true)
or even
(optionBoolean, otherOptionBoolean) == (Some(true), Some(true))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With