Reputation: 267320
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
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
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
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