什么是在akka流中过滤掉左边的惯用方法?

Sto*_*cki 5 scala either akka akka-stream

我有一个流,其中包含大量的值.我正在寻找一种过滤掉Either-Left和Either-Right上的地图的不道德的方法.我想避免类似的事情

final case class Foo(x: Either[String, Int], y:Int)

val foos = functionReturningSeqOfFoo()

Source(foos)
  .filter(_.x.isRight)
  .map(foo => (foo.x.right.get, foo.y))
  .map { case (x, y) =>
    doSomethingWith(x, y)
  }
  .runWith(Sink.seq)
Run Code Online (Sandbox Code Playgroud)

这是一个最小的例子.因为我的流非常长,所以这很混乱,并且感觉不是一个好方法.

顺便说一下,在我的情况下同样适用于Option [T].

lsl*_*lah 4

您可以使用收集

Source(foos).collect { case Foo(Right(x), y) => (x, y) }
Run Code Online (Sandbox Code Playgroud)

或直接使用以下方法转换元组:

Source(foos).collect { case Foo(Right(x), y) => doSomethingWith(x, y) }
Run Code Online (Sandbox Code Playgroud)

collect将删除未定义部分函数的所有对象。