使用for-comprehension,在Scala中尝试和序列

alm*_*dar 13 scala for-comprehension

假设你有很多方法:

def foo() : Try[Seq[String]]
def bar(s:String) : Try[String]
Run Code Online (Sandbox Code Playgroud)

你想做一个for-comprhension:

for {
  list <- foo
  item <- list
  result <- bar(item)
} yield result
Run Code Online (Sandbox Code Playgroud)

当然这不会编译,因为在此上下文中Seq不能与Try一起使用.

任何人都有一个很好的解决方案如何写这个干净而不会分成两个单独的?

我在三分之一的时间里遇到过这种语法问题,并认为现在是时候问这个了.

Jam*_*pic 5

您可以利用Try可以转换为Option, 和Option到 的事实Seq

for {
  list <- foo.toOption.toSeq // toSeq needed here, as otherwise Option.flatMap will be used, rather than Seq.flatMap
  item <- list
  result <- bar(item).toOption // toSeq not needed here (but allowed), as it is implicitly converted
} yield result
Run Code Online (Sandbox Code Playgroud)

这将返回 a (如果Trys 失败,则可能为空)Seq

如果您想保留所有异常详细信息,则需要一个Try[Seq[Try[String]]]. 这不能通过单个理解来完成,所以你最好坚持使用 plain map

foo map {_ map bar}
Run Code Online (Sandbox Code Playgroud)

如果您想以不同的方式混合Trys 和Seqs,事情会变得更加复杂,因为没有自然的方法来展平Try[Seq[Try[String]]]. @Yury 的回答展示了你必须做的事情。

或者,如果您只对代码的副作用感兴趣,您可以这样做:

for {
  list <- foo
  item <- list
  result <- bar(item)
} result
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为foreach类型签名限制较少。

  • 问题是我会丢失异常详细信息。我想要实现的是处理 Seq 中的所有元素,并在任何元素抛出异常时停止。除此之外,感谢 Option 的想法。一个不错的技巧。 (2认同)

Yur*_*riy 5

恕我直言:Try and Seq不仅仅是定义 monad 转换器所需的:

图书馆代码:

case class trySeq[R](run : Try[Seq[R]]) {
  def map[B](f : R => B): trySeq[B] = trySeq(run map { _ map f })
  def flatMap[B](f : R => trySeq[B]): trySeq[B] = trySeq {
    run match {
      case Success(s) => sequence(s map f map { _.run }).map { _.flatten }
      case Failure(e) => Failure(e)
    }
  }

  def sequence[R](seq : Seq[Try[R]]): Try[Seq[R]] = {
    seq match {
      case Success(h) :: tail =>
        tail.foldLeft(Try(h :: Nil)) {
          case (Success(acc), Success(elem)) => Success(elem :: acc)
          case (e : Failure[R], _) => e
          case (_, Failure(e)) => Failure(e)
        }
      case Failure(e) :: _  => Failure(e)
      case Nil => Try { Nil }
    }
  }
}

object trySeq {
  def withTry[R](run : Seq[R]): trySeq[R] = new trySeq(Try { run })
  def withSeq[R](run : Try[R]): trySeq[R] = new trySeq(run map (_ :: Nil))

  implicit def toTrySeqT[R](run : Try[Seq[R]]) = trySeq(run)
  implicit def fromTrySeqT[R](trySeqT : trySeq[R]) = trySeqT.run
} 
Run Code Online (Sandbox Code Playgroud)

在您可以使用 for-comrehension 之后(只需导入您的库):

def foo : Try[Seq[String]] = Try { List("hello", "world") } 
def bar(s : String) : Try[String] = Try { s + "! " }

val x = for {
  item1  <- trySeq { foo }
  item2  <- trySeq { foo }
  result <- trySeq.withSeq { bar(item2) }
} yield item1 + result

println(x.run)
Run Code Online (Sandbox Code Playgroud)

它适用于:

def foo() = Try { List("hello", throw new IllegalArgumentException()) } 
// x = Failure(java.lang.IllegalArgumentException)
Run Code Online (Sandbox Code Playgroud)