Before 2.13
we could access the right value of an Either
as Either.right
, which is now deprecated.
What’s the replacement for this statement?
Before 2.13
we could access the right value of an Either
as Either.right
, which is now deprecated.
What’s the replacement for this statement?
You can use pattern-matching in the Either values:
either match{
case Rigth(a) => doSomething(a)
case Left(b) => doSomething(b)
}
EDIT
This is the link to the scala doc https://www.scala-lang.org/api/current/scala/util/Either.html
You could also use getOrElse, which is often more convenient than right.
It depends what you want to do next.
If you want to map or flatMap, you can just omit it because they exist on Either now and are right-biased.
I just want the plain value to compare it in an unit test.
In the productive code I’d know how to deal with Either.
Compare to Right(x)
or pattern match and compare inside the Right
branch.
If explicit Right comparison or pattern matching isn’t your thing, you could resort to using myEither.toOption.get - which will produce a “None.get” exception if myEither is a Left.
If you’re using scalatest, you can consider using cats.scalatest.EitherValues (instead of org.scalatest.EitherValues, which will produce deprecation warnings on 2.13), which will allow syntax like
myEither.value must be (foo)
and, when myEither is a Left, will produce an error message detailing what was contained in that unexpected Left.
You could also use a pattern, e.g.
val Right(foo) = either
foo shouldBe bar
In Specs2 you can use beRight (and beLeft)
val right3 = Right(3)
val leftError = Left("error")
right3 must beRight
leftError must beLeft
right3 must beRight(3)
leftError must beLeft("error")
https://etorreborre.github.io/specs2/guide/SPECS2-2.4.17/org.specs2.guide.Matchers.html