鉴于以下代码在两种方法中使用Either
,有没有办法在case Left(error) => Left(error)
方法中消除duplicate
,因为它只是通过error
变量?
object HelloScala extends App{
def duplicateAgain(a:Int): Future[Either[String,Int]] = Future {
if (a>0)
Right(a*2)
else
Left("Error")
}
def duplicate(a: Int): Future[Either[String,Int]] = {
val future = duplicateAgain(a)
future.map { either =>
either match {
case Right(response) => Right(response * 2)
case Left(error) => Left(error) // <-- this seems redundant
}
}
}
val future2 = duplicate(-1)
future2.map { either =>
either match {
case Right(response) => println(response)
case Left(error) => println(error)
}
}
Thread.sleep(10000)
}
答案 0 :(得分:8)
使用map
- 替换
either match {
case Right(response) => Right(response * 2)
case Left(error) => Left(error) // <-- this seems redundant
}
与
either.map(response => response * 2)
正如Either
的文档所说
是右偏,这意味着右被认为是默认情况下进行操作。如果左,地图和 flatMap 等操作会使左值保持不变