質問

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))
役に立ちましたか?

解決

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
}

他のヒント

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
    }
  }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top