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