Last active
April 1, 2022 06:02
-
-
Save hussachai/c15d374e265baaeec379de6edc7c1fe9 to your computer and use it in GitHub Desktop.
Error Handling in Rust that Every Beginner should Know (Scala way)
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 square(s: String): Try[Double] = Try { | |
val i = s.toDouble | |
i * i | |
} | |
def calculate(x: String, y: String): Try[Double] = { | |
for { | |
x <- square(x) | |
y <- square(y) | |
} yield Math.sqrt(x + y) | |
} | |
println(calculate("2", "2")) // Success(2.828) | |
println(calculate("2", "x")) // Failure(java.lang.NumberFormatException) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment