消除任何一个中的冗余Left

时间:2018-03-16 12:49:50

标签: scala

鉴于以下代码在两种方法中使用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)
}

1 个答案:

答案 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 等操作会使值保持不变