Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently check that two Options is defined?

Suppose, I have two options:

val a: Option = Some("string")
val b: Option = None

How to efficiently check that both a and b is defined?

I now that I can wrote something like this:

if (a.isDefined && b.isDefined) {
....
}

But, it looks ugly and not efficiently.

So. How to do that? What is best practices?

UPDATE

I want to do my business logic.

if (a.isDefined && b.isDefined) {
   ....

   SomeService.changeStatus(someObject, someStatus)

   ...
   /* some logic with a */
   /* some logic with b */
}
like image 650
atygaev.mi Avatar asked Dec 26 '22 10:12

atygaev.mi


2 Answers

Use a for comprehension:

val a: Option[String] = Some("string")
val b: Option[String] = None

for {
    aValue <- a
    bValue <- b
} yield SomeService.changeStatus(someObject, someStatus)
like image 194
Noah Avatar answered Jan 12 '23 15:01

Noah


Alternatively, just for fun,

scala> val a: Option[String] = Some("string")
a: Option[String] = Some(string)

scala> val b: Option[String] = None
b: Option[String] = None

scala> val c = Option("c")
c: Option[String] = Some(c)

scala> (a zip b).nonEmpty
res0: Boolean = false

scala> (a zip c).nonEmpty
res1: Boolean = true

scala> (a zip b zip c).nonEmpty
res2: Boolean = false
like image 42
som-snytt Avatar answered Jan 12 '23 15:01

som-snytt