【问题标题】:Scala: Convert Future[Option[List[User]]] to Future[Map[Long, User]]Scala:将 Future[Option[List[User]]] 转换为 Future[Map[Long, User]]
【发布时间】:2014-03-16 18:13:39
【问题描述】:

User 是一个案例类:

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

搜索函数返回Future[Option[List[User]]]。从这个未来,我想提取一个Map[Long, User],以 id 作为键。现在我正在使用以下方法来提取地图,但应该有更好的方法来完成它。

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

【问题讨论】:

    标签: scala future


    【解决方案1】:

    这个怎么样?

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

    【讨论】:

      【解决方案2】:

      我认为这应该可以满足您的需求:

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

      【讨论】:

        猜你喜欢
        • 2016-08-01
        • 1970-01-01
        • 2020-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多