在 Either 中通过 Left 语句

Passing through Left statement in Either

鉴于这两种使用 Either 的方法,在第二种方法中我需要使用 Left(error) => Left(error) 转发错误。有没有办法在第二种方法(或使用更优雅的代码)中省略它,因为语句只需要通过?

  trait Error
  case class ErrorClass (msg: String) extends Error

  def intFunction(i:Int) : Either[ErrorClass,Int] = {
    if (i>0)
        Right(i)
    else
        Left(ErrorClass("error"))
  }

  def multiplier(j:Int) : Either[ErrorClass,Int] = {
      val either = intFunction(2)
      either match {
        case Right(i) => Right(i*j)
        case Left(error) => Left(error)
      }
  }

从 scala 2.12 开始,Either 是 right-biased,这意味着您可以 .map() 覆盖它并且只有当它是 Right 时才会应用该函数:

trait Error
case class ErrorClass(msg: String) extends Error

def intFunction(i: Int): Either[ErrorClass, Int] = {
  if (i > 0)
    Right(i)
  else
    Left(ErrorClass("error"))
}

def multiplier(i: Int, j: Int): Either[ErrorClass, Int] = {
  val either = intFunction(i)
  either.map(_ * j)
}

println(multiplier(10, 10))  // Right(100)
println(multiplier(-1, 10))  // Left(ErrorClass(error))

如果您使用的是 scala 2.11-,您需要明确并在映射之前访问 RightProjection,因为 Either 不是 right-biased:

def multiplier(i: Int, j: Int): Either[ErrorClass, Int] = {
  val either = intFunction(i)
  either.right.map(_ * j)
}