Scala:将Future [Option [List [User]]]转换为Future [Map [Long,User]]

时间:2014-03-16 00:32:59

标签: scala future

User是一个案例类:

case class User(id: Long, firstName: String, lastName: String)

搜索功能返回Future[Option[List[User]]]。从这个未来,我想提取一个{id为密钥的Map[Long, User]。现在我正在使用以下方式来理解提取Map,但应该有更好的方法来实现它。

def users: Future[Map[Long, User]] = { 
  for {
    future <- search(...)
  } yield for {
    users <- future
  } yield for {
    user <- users
  } yield user.id -> user
}.map(_.map(_.toMap))

2 个答案:

答案 0 :(得分:2)

这个怎么样?

def users: Future[Map[Long, User]] = search().map { opt =>
  val list = for {
    users <- opt.toList
    user <- users
  } yield (user.id, user)
  list.toMap
}

答案 1 :(得分:1)

我认为这应该做你需要的:

def users: Future[Map[Long, User]] = {
  search().map { searchResult =>
    searchResult match {
      case Some(list) => list.map { u => (u.id, u) }.toMap
      case _ => Map.empty
    }
  }
}