Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. import scala.util.{Try, Success, Failure}
  2.  
  3. def option(b: Boolean) = if (b) Some("option") else None
  4. def either(b: Boolean) = if (b) Right("either") else Left(new Exception("either"))
  5. def exception(b: Boolean) = if (b) "exception" else throw new Exception("exception")
  6.  
  7. // def toEither[A](t: Try[A]) = t.transform({s => Success(Right(s))}, {f => Success(Left(f))}).get.right
  8. def toEither[A](t: Try[A]) = (t match {case Success(v) => Right(v) case Failure(e) => Left(e)}).right
  9.  
  10. val ft = Seq(false, true)
  11. for (bOpt <- ft; bEit <- ft; bExc <- ft) {
  12. println()
  13. println(s"$bOpt $bEit $bExc")
  14. println(resultOption(bOpt, bEit, bExc))
  15. println(resultEither(bOpt, bEit, bExc))
  16. }
  17.  
  18. // Option (success or not)
  19. def resultOption(bOpt: Boolean, bEit: Boolean, bExc: Boolean) = {
  20. for {
  21. opt <- option(bOpt)
  22. eit <- either(bEit).right.toOption
  23. exc <- Try(exception(bExc)).toOption
  24. } yield (s"$opt $eit $exc")
  25. }
  26.  
  27.  
  28. // Either (success or individual exception)
  29. def resultEither(bOpt: Boolean, bEit: Boolean, bExc: Boolean) = {
  30. for {
  31. opt <- option(bOpt).toRight(new Exception("option")).right
  32. eit <- either(bEit).right
  33. exc <- toEither(Try(exception(bExc)))
  34. } yield (s"$opt $eit $exc")
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement