Question: Clean way to handle future and option

Question

Clean way to handle future and option

Answers 3
Added at 2016-12-31 21:12
Tags
Question

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]]
Answers
nr: #1 dodano: 2016-12-31 21:12

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

nr: #2 dodano: 2016-12-31 23:12
for (maybeUser <- getUser(1);
     user <- maybeUser) yield someFunction1(user)

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

nr: #3 dodano: 2017-01-01 09:01

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]
 }
Source Show
◀ Wstecz