Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created September 6, 2012 12:04
Show Gist options
  • Save kmizu/3655519 to your computer and use it in GitHub Desktop.
Save kmizu/3655519 to your computer and use it in GitHub Desktop.
Avoid nested pattern match with Either
> scala UseEither some
some success
> scala UseEither none
failure
> scala UseEither hoge
java.lang.Exception: example exception
object UseEither {
def doSomething(arg: String): Either[Throwable, Option[String]] = arg match {
case "none" => Right(None)
case "some" => Right(Some("some"))
case _ => Left(new Exception("example exception"))
}
def main(args: Array[String]) {
val somethingEither = for {
s <- doSomething(args(0)).right
} yield s.map(_ + " success").getOrElse("failure")
println(somethingEither.fold(
l => l.toString,
r => r
))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment