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
getOrElsefor aLeftProjection[A, B]is:i.e. it expects the argument to be of some type
AAwhich is a supertype ofA.In the first example, you left out type annotations, allowing the compiler to infer
NothingforA. Then, you supplied an argument of typeLeftProjection[Nothing, Int].Because
Nothingis 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
StringandLeftProjection[String, Int]isSerializable.So, if you want to chain
Eithers, you need a method which can take anotherEither[A, B], not just anAorB.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 ofAorB(or some supertype thereof), you can chain yourEithers.