鉴于这三种方法返回Future[Either[String,Int]]
:
def greater(x:Int): Future[Either[String,Int]] = Future {
if (x>0)
Right(x)
else
Left("Is not greater")
}
def less(x:Int): Future[Either[String,Int]] = Future {
if (x<0)
Right(x)
else
Left("Is not less")
}
def zero(x:Int): Future[Either[String,Int]] = Future {
if (x==0)
Right(x)
else
Left("Is not zero")
}
调用上述三个方法的以下方法会引发编译错误:
def evaluate(x:Int): Future[Either[String,Int]] = {
val future = greater(x)
future.flatMap { either =>
either.right.flatMap { response => // <-- error in this line
val future2 = less(response)
future2.map { either2 =>
either2.right.map { response2 => zero(response2) }
}
}
}
}
错误:
类型不匹配; found:scala.util.Either [String,Nothing]: scala.concurrent.Future [要么[字符串,INT]]
如何解决evaluate
方法?
答案 0 :(得分:2)
Monad变形金刚的经典案例。
使用猫的EitherT
val result =
for {
a <- EitherT(greater(x))
b <- EitherT(less(a))
c <- EitherT(zero(b))
} yield c
最终价值:result.value
为什么选择E?T?
Either
在另一个看似单身的Future
内。因此,EitherT
可以使用。