Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.util.{Try, Success, Failure}
- def option(b: Boolean) = if (b) Some("option") else None
- def either(b: Boolean) = if (b) Right("either") else Left(new Exception("either"))
- def exception(b: Boolean) = if (b) "exception" else throw new Exception("exception")
- // def toEither[A](t: Try[A]) = t.transform({s => Success(Right(s))}, {f => Success(Left(f))}).get.right
- def toEither[A](t: Try[A]) = (t match {case Success(v) => Right(v) case Failure(e) => Left(e)}).right
- val ft = Seq(false, true)
- for (bOpt <- ft; bEit <- ft; bExc <- ft) {
- println()
- println(s"$bOpt $bEit $bExc")
- println(resultOption(bOpt, bEit, bExc))
- println(resultEither(bOpt, bEit, bExc))
- }
- // Option (success or not)
- def resultOption(bOpt: Boolean, bEit: Boolean, bExc: Boolean) = {
- for {
- opt <- option(bOpt)
- eit <- either(bEit).right.toOption
- exc <- Try(exception(bExc)).toOption
- } yield (s"$opt $eit $exc")
- }
- // Either (success or individual exception)
- def resultEither(bOpt: Boolean, bEit: Boolean, bExc: Boolean) = {
- for {
- opt <- option(bOpt).toRight(new Exception("option")).right
- eit <- either(bEit).right
- exc <- toEither(Try(exception(bExc)))
- } yield (s"$opt $eit $exc")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement