Last active
March 29, 2019 23:52
-
-
Save neilchaudhuri/5c4cc893d46e107aac4ee163f22e9d0d to your computer and use it in GitHub Desktop.
Idiomatic Scala error handling
This file contains 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
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