ps0604
ps0604

Reputation: 1081

Passing through Left statement in Either

Given these two methods that use Either, in the second method I need to forward the error using Left(error) => Left(error). Is there a way to omit this in the second method (or use more elegant code) as the statement just needs to be passed through?

  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)
      }
  }

Upvotes: 0

Views: 689

Answers (1)

Marth
Marth

Reputation: 24832

Starting with scala 2.12, Either is right-biased, meaning you can .map() over it and the function will only be applied if it's a 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))

If you're using scala 2.11-, you need to be explicit and access the RightProjection before mapping over it, as the Either is not right-biased:

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

Upvotes: 1

Related Questions