The error message says that you cannot use Either
as a case class constructor. IOW, Either
is equivalent to an abstract class since you have encoded it as a trait with its own implementable methods. Let's assume you have the following encoded representation of Either
, Left
and Right
:
sealed trait Either[+E, +A] {
def map[B](f: A => B): Either[E, B] = ???
}
// Left signifies error condition
// Right is something Right, along with its message.
case class Left[+E](err: E) extends Either[E,Nothing]
case class Right[+E](msg: E) extends Either[Nothing,E]
You can write the map
function as:
def map[B](f: A => B): Either[E, B] = this match {
case Right(v) => Right(f(v))
case Left(e) => Left(e)
}
Here I'm simply saying that if you encounter something that's supposed to be a right value, perform some function computation on it and return it exactly as it should be - a Right
. Since Either
is a sealed trait
(mainly for convenience), the only other type could be a Left
which I return as is. Read more about Either