【问题标题】:Mapping a Future[List[ObjectOne]] into Future[List[ObjectTwo]] with an inner list attribute - one call chain使用内部列表属性将 Future[List[ObjectOne]] 映射到 Future[List[ObjectTwo]] - 一个调用链
【发布时间】:2020-07-04 02:57:55
【问题描述】:
case class ObjectOne(id: String, numbers: List[Int])
case class ObjectTwo(id: String, numberOfFives : Int)

val start : Future[List[ObjectOne]] = ...
val end : Future[List[ObjectTwo]] = start. ?????

我正在尝试将开始对象变成结束对象。结束对象应包含来自 ObjectOne 的 id 以及数字 5 在 objectOne.numbers 上出现的次数。

我找不到在简单的调用链中编写它的方法

【问题讨论】:

    标签: scala functional-programming future


    【解决方案1】:

    假设您有一个如下所示的转换函数:

    def objectOneToObjectTwo(one: ObjectOne): ObjectTwo = ???
    

    然后Future[List[_]] 转换看起来像:

    // put proper execution context or use global. It used in `Future#map` operation
    implicit val ec: ExecutionContext = ???
    
    val start : Future[List[ObjectOne]] = ???
    val end : Future[List[ObjectTwo]] = start.map(_.map(objectOneToObjectTwo))
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      被另一张地图闲置的地图表明人们可能会考虑使用变压器,例如Nested

      val end = Nested(start).map { 
        case ObjectOne(id, numbers) => ObjectTwo(id, numbers.count(_ == 5)) 
      }
      

      scastie

      【讨论】:

        猜你喜欢
        • 2022-07-26
        • 1970-01-01
        • 1970-01-01
        • 2018-06-29
        • 1970-01-01
        • 2018-03-21
        • 2022-01-03
        • 2019-11-20
        • 2023-02-22
        相关资源
        最近更新 更多