Created
September 6, 2012 12:04
-
-
Save kmizu/3655519 to your computer and use it in GitHub Desktop.
Avoid nested pattern match with Either
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> scala UseEither some | |
some success | |
> scala UseEither none | |
failure | |
> scala UseEither hoge | |
java.lang.Exception: example exception |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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