No, if you do it this way, you can’t leave out the type.
The type of Left("No number")
is inferred to be Either[String, Nothing]
. From just Left("No number")
the compiler can’t know that you want the second type of the Either
to be Int
, and type inference doesn’t go so far that the compiler will look at the whole method and decide it should be Either[String, Int]
.
You could do this in a number of different ways. For example with pattern matching:
def foo(ox: Option[Int]): Either[String, Int] = ox match {
case Some(x) => Right(x)
case None => Left("No number")
}
Or with an if
expression:
def foo(ox: Option[Int]): Either[String, Int] =
if (ox.isDefined) Right(ox.get) else Left("No number")
Or with Either.cond
:
def foo(ox: Option[Int]): Either[String, Int] =
Either.cond(ox.isDefined, ox.get, "No number")