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

如何从一个返回未来的方法中摆脱出来?

  •  -1
  • Omnipresent  · 技术社区  · 7 年前
    def myMethod(myType: String) :Future[Future[Either[List[MyError], MyClass]]] {
       for {
         first <- runWithSeq(firstSource)
       }
       yield {
         runWithSeq(secondSource) 
         .map {s -> 
            val mine = MyClass(s.head, lars)
            val errors = myType match {
              case "all" => Something.someMethod(mine)
            }
            (s, errors)
         } 
         .map { x => 
            x._2.leftMap(xs => { 
              addInfo(x._1.head, xs.toList)
            }).toEither
         }
       }
    }
    
    for {
      myStuff <- myMethod("something")
    } yield {
      myStuff.collect {
       case(Left(errors), rowNumber) => 
        MyCaseClass(errors, None) //compilation error here
      }
    }
    

    我在上得到编译错误 MyCaseClass 那个 expected: List[MyError], found: Any

    签字 蛋壳 是:

    case class MyCaseClass(myErrors: List[ValidationError])
    

    我怎样才能把这个修好,这样我就可以正确地打电话了 蛋壳 里面 yield ?

    2 回复  |  直到 7 年前
        1
  •  1
  •   jwvh    7 年前

    您的代码示例没有多大意义,也没有编译,但是如果 runWithSeq() 返回 Future 那么你应该能够消除双重性 未来 像这样的返回类型。

    for {
      _    <- runWithSeq(firstSource)
      scnd <- runWithSeq(secondSource)
    } yield { ...
    
        2
  •  1
  •   Ivan Aristov    7 年前

    您的示例很难粘贴和修复

    Abstact示例 C类可能是你想要的

    def test(testval: Int)(implicit ec: ExecutionContext): Future[Future[Either[String, Int]]] = {
      Future(Future{
        if (testval % 2 == 0) Right(testval) else Left("Smth wrong")
      })
    }
    
    implicit class FutureEitherExt[A, B](ft: Future[Either[A, B]]) {
      def EitherMatch[C](f1: A => C, f2: B => C)(implicit ec: ExecutionContext): Future[C] = {
        ft.map {
          case Left(value) => f1(value)
          case Right(value) => f2(value)
        }
      }
    }
    
    val fl: Future[Either[String, Int]] = test(5).flatten
    
    val result: Future[String] = fl.EitherMatch(identity, _.toString)
    
    推荐文章