Reputation: 3771
User
is a case class:
case class User(id: Long, firstName: String, lastName: String)
A search function returns Future[Option[List[User]]]
. From this future I want to extract a Map[Long, User]
with the id as key. Right now I am using for comprehension the following way to extract the Map but there should be a better way to do it.
def users: Future[Map[Long, User]] = {
for {
future <- search(...)
} yield for {
users <- future
} yield for {
user <- users
} yield user.id -> user
}.map(_.map(_.toMap))
Upvotes: 1
Views: 701
Reputation: 1786
What about this?
def users: Future[Map[Long, User]] = search().map { opt =>
val list = for {
users <- opt.toList
user <- users
} yield (user.id, user)
list.toMap
}
Upvotes: 2
Reputation: 3294
I think this should do what you need:
def users: Future[Map[Long, User]] = {
search().map { searchResult =>
searchResult match {
case Some(list) => list.map { u => (u.id, u) }.toMap
case _ => Map.empty
}
}
}
Upvotes: 1