代码之家  ›  专栏  ›  技术社区  ›  Anthony

如何处理将来的流以创建具有List属性的类的实例

  •  1
  • Anthony  · 技术社区  · 6 年前

    我有一个方法,它以未来为参数,并且在其中也有未来。我想从这个方法创建一个列表,这样它就可以从将来传入的值中获取值。

    案例类

    case class Color (colorName: String)
    case class Shade (shadeName: String)
    case class ColoShade (color: Color, shades: List[Shade])
    

    方法

    val shadesFuture: Future[Seq[Shade]] = {
        val larSource: Future[Seq[LoanApplicationRegister]] =
          getMySource(ctx, id)
            .map(_.utf8String)
            .map(_.trim)
            .map(s => ShadeParser(s))
            .collect {
              case Right(shade) => shade
            }
            .runWith(Sink.seq)
    }
    
    //call the method
    myMethod(shadesFuture)
    
    //method definition
    def myMethod(shadesFuture: Future[Seq][Shade]])
      :Future[ColorShade] {
        colorFuture
          .map(_.utf8String)
          .map(_.trim)
          .map { s =>
            ColorParser(s)
          }
          .collect {
            case Right(c) => c
          }
          .map { c =>  
             //How can I make an instance of ColorSade here? 
             //I tried 
             val colorShade = ColorShade(c, shadesFuture) 
             //but this doesn't work  
    
             //I would like to change this to instead be someOtherMethod(colorShade.c)
             someOtherMethod(c) 
          }
    }
    

    问题

    我怎样才能正确返回 ColorShade myMethod 这样 shades 属性是传入参数的输出 shadesFuture 是吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Dima    6 年前

    我不确定我明白你的意思…但我认为你在找这样的东西:

     def myMethod(shadesFuture: Future[Seq[Shade]]) : Future[ColorShade] = for {
       shades <- shadesFuture
       color <- colorFuture.map(...) // whatever the transformations you wanted
       transformedColor = ColorParser(color.utf8String.trim) // or you can do them like this
    
       colorShade = ColorShade(color, shades)
       // whatever you wanted to do with it here
       _ = someOtherMethod(colorShade.c, colorShade.shades)
     } yield colorShade // or whatever you need to return. The result of this is `Future[ColorShade]`
    

    这被称为“为了理解”,在句法上对一堆嵌套的 .flatMap 电话。你也可以把它写得很明确(这不完全是理解的东西,但功能上是等价的):

     shadesFuture
        .flatMap { shades => 
           colorFuture
             .map(...)  // transform, whatever
             .map(ColorShade(_, shades)
        }