此代码打印 List(1, 2, ())
def f1(i:Int): Either[String,Int] = if (i > 0) Right(1) else Left("error 1")
def f2(i:Int): Either[String,Int] = if (i > 0) Right(2) else Left("error 2")
def f3(i:Int): Either[String,Int] = if (i > 0) Right(3) else Left("error 3")
val seq = Seq(f1(1),f2(1),f3(-1))
val x = seq.map { f => if (f.isRight) f.right.get }
println(x)
我需要一个由
isRight
过滤的数组为真,消除任何其他值。在上面的例子中,我需要的结果是 List(1, 2)
.如何实现?
最佳答案
使用 collect
和模式匹配以选择您感兴趣的案例。
seq.collect { case Right(value) => value}
让我们试穿
Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)
def f1(i:Int): Either[String,Int] = if (i > 0) Right(1) else Left("error 1")
def f2(i:Int): Either[String,Int] = if (i > 0) Right(2) else Left("error 2")
def f3(i:Int): Either[String,Int] = if (i > 0) Right(3) else Left("error 3")
val seq = Seq(f1(1),f2(1),f3(-1))
// Exiting paste mode, now interpreting.
f1: (i: Int)Either[String,Int]
f2: (i: Int)Either[String,Int]
f3: (i: Int)Either[String,Int]
seq: Seq[Either[String,Int]] = List(Right(1), Right(2), Left(error 3))
scala> seq.collect { case Right(value) => value }
res0: Seq[Int] = List(1, 2)
函数式编程是关于表达式而不是语句
在
val x = seq.map { f => if (f.isRight) f.right.get }
以下返回
Unit
如果 f 不对。所以,你得到 Unit
作为第三个值。if (f.isRight) f.right.get
功能方式是使用还有其他部分。但是在这种情况下,没有有意义的 else 情况。
关于scala - 从任一序列中只获取正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49200676/