Search code examples
scalascala-option

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 */
}

Solution

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