Say I have a class with multiple parameters:
case class Foo(a: String, b: String, c: String, d: String, ... )
Now say I want to parse an instance of Foo
from a Map[String, String]
:
// returns either the parsed Foo as Right, or error message as Left
// example: Map("a" -> "1", "b" -> "2" ... ) returns Foo("1", "2", ... )
def parse(fromMap: Map[String, String]): Either[String, Foo]
The names of the keys are irrelevant; this is not a reflection type of question.
My implementation looks something like this:
fromMap.get("a") match {
case None => Left("couldn't find a")
case Some(a) => fromMap.get("b") match {
...
case Some(last) => Right(Foo(a, ... , last))
}
}
But when there are many parameters, the indentation is just too extreme, and that makes it hard to understand the logic of the method (it may be a bit more complex than just a map lookup).
Can you think of a more readable code for such a use-case?