Why when I type this all works fine?
Right(2).left getOrElse Right(4).left getOrElse Left("Error")
but when I type this compilation fails?
Right[String, Int](2).left getOrElse Right[String, Int](4).left getOrElse Left[String, Int]("Error")
Compilation error:
value getOrElse is not a member of java.io.Serializable
println(RightString, Int.left getOrElse RightString, Int.left getOrElse LeftString, Int)
So I can't chain getOrElse
method call
The signature of
getOrElse
for aLeftProjection[A, B]
is:i.e. it expects the argument to be of some type
AA
which is a supertype ofA
.In the first example, you left out type annotations, allowing the compiler to infer
Nothing
forA
. Then, you supplied an argument of typeLeftProjection[Nothing, Int]
.Because
Nothing
is a subtype of all types,LeftProjection[Nothing, Int]
is trivially a supertype! This special case in the type system means that it type-checked almost by accident.However, the most specific common supertype of
String
andLeftProjection[String, Int]
isSerializable
.So, if you want to chain
Either
s, you need a method which can take anotherEither[A, B]
, not just anA
orB
.The method you seem to want would look like this:
(You could similarly write
rightOrElse
, which is a more common use case.)This becomes syntactically a bit more usable if you make it an extension method, using implicits.
Because this expects
Either[A, B]
for both operands, instead ofA
orB
(or some supertype thereof), you can chain yourEither
s.