Blankman
Blankman

Reputation: 267320

Clean way to handle future and option

My code block looks like this currently which seems ugly:

for {
  maybeUser <- getUser(1)
} yield {
  if (maybeUser.isDefined) {
     someFunction1(maybeUser.get)
  } else None
}

Where getUser looks like:

def getUser(id: Int): Future[Option[user]]

Upvotes: 3

Views: 146

Answers (3)

Orar
Orar

Reputation: 958

You can try a more readable one.

val mayBe = getUser(1)
(for {
     m <- maybe
     if m.isDefined
   } yield m.get //Seq(m.get)
 ).recover {
    _=> ??? //Seq.empty[MType]
 }

Upvotes: -1

evan.oman
evan.oman

Reputation: 5572

You should be able to something like:

for {
  maybeUser <- getUser(1)
} yield {
  maybeUser.map(someFunction1)
}

This will yield an Option[T] (where T is the return type of someFunction1) which should be what you want.

For a great summary of Option patterns I can't recommend this article highly enough: Your Options Don't Match

Upvotes: 4

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25939

for (maybeUser <- getUser(1);
     user <- maybeUser) yield someFunction1(user)

Assuming someFunction1(user) returns an Option something (otherwise call Some(someFunction1(user))

Upvotes: 0

Related Questions