如何处理将来的流以创建具有列表属性的类的实例 [英] How to process future stream to create an instance of class with list property

查看:61
本文介绍了如何处理将来的流以创建具有列表属性的类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,该方法将future作为参数,并且内部也包含future。我想通过此方法创建一个列表,以便它从传入的将来获取值。

I have a method that is takes in a future as parameter and also has a future inside it. I want to create a list from this method such that it takes values from the future that is passed in.

案例类

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 c $ c> myMethod ,这样 shades 属性就是传入的参数 shadesFuture

How can I correctly return ColorShade from myMethod such that the shades property is the output from the passed in parameter shadesFuture?

推荐答案

我不确定我是否理解您的意思……但是我认为您正在寻找这样的东西:

I am not sure I understand what you mean ... But I think you are looking for something like this:

 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 调用。您也可以明确地编写它(这并不是理解所要理解的,但在功能上是等效的):

This is called "for-comprehension" and is syntactic sure for a bunch of nested .flatMap calls. You could also writer it explicitly (this is not exactly what for-comprehension is desugared into, but functionally equivalent):

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

这篇关于如何处理将来的流以创建具有列表属性的类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆