Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created September 29, 2018 18:42
Show Gist options
  • Select an option

  • Save JoolsF/88351eac3ae57e2ef59a1f3b3015ddbd to your computer and use it in GitHub Desktop.

Select an option

Save JoolsF/88351eac3ae57e2ef59a1f3b3015ddbd to your computer and use it in GitHub Desktop.
cats either extensions 1
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