How to use Either in scala


How to use Either in scala



I want to do similar like below


def run(list : List(String)){

val map = Map[String,String] (immutable map)

list.foreach{
val x = someOtherMethod()

val result = processMap(x,map) // please see below method for details

//Not sure how to use result here
1) if ProcessMap returns Map then I want to assign returned MAP to map val
2) otherwise don't do anything

}

writeOutput(x,map)

}

def processMap(x :boolean, map : Map[String,String]) : Either[Option(String) , Map[String,String]]
{

x match {
case true => {
do some processing and update map and return

Right(map ++ newGeneratedMap)
}
case _ => Left(None)
}


}



In above example I want to use Map as Java static variable. I want to pass Map to a method based on some condition it may get updated and may not. If its updated then only I want to return it and pass it to next method.If map is not updated then I want to pass existing map to method.



Main Question : How can I access output of result (left / right) here ?





Your code won't compile. It has weird stuff such as Either[Option(None). Please fix it
– mfirry
Jun 29 at 8:51



Either[Option(None)





Thanks, I edited question
– user2895589
Jun 29 at 8:53





Still doesn't compile. You haven't said what things like writeOutput and someOtherFunction are meant to do, or even their expected return types. Also, why are you doing Left(None)? Wouldn't it make more sense to just use Options if you are just storing a None in the Left?
– James Whiteley
Jun 29 at 9:51


writeOutput


someOtherFunction


Left(None)


None


Left





In terms of getting the value out of a Left/Right, you can do something like this: say you have a value val value: Either[Int, Int] = Left(1). If you know that it is a Left, you can just do something like value.left.get (will throw Exception if not Left). If you are unsure whether you are getting a Left or a Right, you could do something like value.right.getOrElse(value.left.get) (would return 1) or if(value.isRight) ... else .... Note that convention says that Eithers are usually Either[Throwable, {something else}], so the value.left.get would usually get an exception.
– James Whiteley
Jun 29 at 9:59


val value: Either[Int, Int] = Left(1)


value.left.get


value.right.getOrElse(value.left.get)


if(value.isRight) ... else ...


Either[Throwable, {something else}]


value.left.get





Possible duplicate of Getting Value of Either
– James Whiteley
2 days ago









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV