Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying Option[Boolean] expression in Scala

I have code like that:

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

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

like image 625
Ava Avatar asked Dec 03 '20 09:12

Ava


People also ask

What is an option in Scala?

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.

How do you use isempty in Scala?

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

How do I get an option value from a map?

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).

What are the rules for simplification of Boolean expressions in KMAP?

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.


Video Answer


3 Answers

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.

like image 111
Tomer Shetah Avatar answered Oct 18 '22 15:10

Tomer Shetah


This is perhaps a bit clearer:

optionBoolean.contains(true) && otherOptionBoolean.contains(true)
like image 43
Tim Avatar answered Oct 18 '22 16:10

Tim


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))
like image 31
Seth Tisue Avatar answered Oct 18 '22 16:10

Seth Tisue