Skip to content

Instantly share code, notes, and snippets.

@neilchaudhuri
Last active March 29, 2019 23:52
Show Gist options
  • Save neilchaudhuri/5c4cc893d46e107aac4ee163f22e9d0d to your computer and use it in GitHub Desktop.
Save neilchaudhuri/5c4cc893d46e107aac4ee163f22e9d0d to your computer and use it in GitHub Desktop.
Idiomatic Scala error handling
import scala.util.{Failure, Success, Try}
def squareRoot(value: Int): Try[Double] = {
if (value >= 0) {
Success(Math.sqrt(value))
} else {
Failure(new IllegalArgumentException("Value cannot be negative"))
}
}
val sum = for {
a <- squareRoot(4)
b <- squareRoot(16)
} yield a + b
sum.map(s => s"The result is $s") match {
case Success(result) => result
case Failure(t) => t.getMessage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment