Created
September 29, 2018 18:42
-
-
Save JoolsF/88351eac3ae57e2ef59a1f3b3015ddbd to your computer and use it in GitHub Desktop.
cats either extensions 1
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
| def squareString(s: String, p: Int => Boolean): Either[String, Int] = { | |
| Either.fromTry( // Either from Try | |
| Try { | |
| val i = s.toInt | |
| i * i | |
| } | |
| ).leftMap { case _: NumberFormatException => "Boom - number format exception!" } // Left map | |
| }.ensure("result must not equal 9")(p) // Predicate to check with result satisfies a predicate | |
| val p: Int => Boolean = _ != 9 | |
| squareString("2", p) // Right(4) | |
| squareString("2!", p) // Left(Boom - number format exception!!) | |
| squareString("3", p) // Left(must not equal 9) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment