質問

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

I was looking at this and needed to handle each combination differently, so I went for a match:

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

(a, b) match {
  case (Some(aStr), Some(bStr)) => ???
  case (Some(aStr), None      ) => ???
  case (None,       Some(bStr)) => ???
  case (None,       None      ) => ???
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top