Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Option to Either in Scala

Suppose I need to convert Option[Int] to Either[String, Int] in Scala. I'd like to do it like this:

def foo(ox: Option[Int]): Either[String, Int] =   ox.fold(Left("No number")) {x => Right(x)} 

Unfortunately the code above doesn't compile and I need to add type Either[String, Int] explicitly:

ox.fold(Left("No number"): Either[String, Int]) { x => Right(x) } 

Is it possible to convert Option to Either this way without adding the type ?
How would you suggest convert Option to Either ?

like image 278
Michael Avatar asked Jan 10 '16 14:01

Michael


People also ask

What is either in scala?

In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared.

What is getOrElse in scala?

As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value.

How do I use options in scala?

The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.


1 Answers

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") 
like image 129
Jesper Avatar answered Sep 19 '22 13:09

Jesper