DCKing
DCKing

Reputation: 4273

Succinctly matching several Options at the same time

When you have an Option aOpt and you're only interested in doing something if it actually contains something, you can do the following:

aOpt match {
   case Some(a) => foo(a)  // do something
   case None => // do nothing
}

Which of course should be shortened to:

aOpt.foreach(a => foo(a))

Now say I have two Options aOpt and bOpt. I'm interested in doing something only if both of these Options actually contain an object.

So I write

(aOpt, bOpt) match {
   case (Some(a), Some(b)) => foo(a, b) // Do something
   case _ => // Do nothing
}

How can I shorten this to fewer lines? Or how can I at least omit the useless case _ => line without warnings?

Upvotes: 2

Views: 91

Answers (1)

senia
senia

Reputation: 38045

for-comprehension

for{
  a <- aOpt
  b <- bOpt
} foo(a, b)

scalaz

Operator |@|

import scalaz._, Scalaz._
(aOpt |@| bOpt)(foo)

Method ^

^(aOpt, bOpt)(foo)

Operator tuple

val abOpt = aOpt tuple bOpt // Option[(A, B)]
abOpt.foreach( case (a, b) => foo(a, b) ) // or
abOpt.foreach( (foo _) tupled _ )

Upvotes: 5

Related Questions