Created
February 4, 2022 16:49
-
-
Save sshark/6ea511b7df8c9a475bb150350835a88c to your computer and use it in GitHub Desktop.
Throwing Exception vs Using Either
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
object FooBar { | |
// Basically Java code written using Scala syntax. Similar to using if to check for errors i.e. if (err != nil) {...} | |
object Foo extends App { | |
def addMin(a: Int, b: Int): Int = | |
if (a + b < 10) throw new Exception("Sum is less than 10") else a + b | |
def mulMin(a: Int, b: Int): Int = | |
if (a * b < 100) throw new Exception("Product is less than 100") else a * b | |
def plus10(a: Int, b: Int): Int = | |
try { | |
val x = addMin(a, b) | |
try { | |
mulMin(5, x) + 10 | |
} catch { | |
case _: Exception => -2 // forces a fallback value. What if there is no reasonable fallback value? | |
} | |
} catch { | |
case _: Exception => -1 // forces a fallback value | |
} | |
println(plus10(20, 10)) | |
} | |
// Not reproducible in Java even though Either can be found in Vavr. There is no concept of 'implicit' in Java | |
object Bar extends App { | |
// for fallback value route | |
implicit def foo[A, B](e: Either[A, B]) = new { | |
def recover(f: => B): Either[A, B] = e match { | |
case r@Right(_) => r | |
case Left(_) => Right(f) | |
} | |
} | |
def addMin(a: Int, b: Int): Either[Throwable, Int] = | |
if (a + b < 10) Left(new Exception("Sum is less than 10")) else Right(a + b) | |
def mulMin(a: Int, b: Int): Either[Throwable, Int] = | |
if (a * b < 100) Left(new Exception("Product is less than 100")) else Right(a * b) | |
def plus10Fallback(a: Int, b: Int): Either[Throwable, Int] = | |
addMin(a, b).recover(-1).flatMap(x => mulMin(20, x)).recover(-2) | |
def plus10(a: Int, b: Int): Either[Throwable, Int] = | |
addMin(a, b).flatMap(x => mulMin(20, x)) | |
plus10Fallback(2, 1).fold(t => println(t.getMessage), println) // with fallback values | |
plus10(2, 1).fold(t => println(t.getMessage), println) // no fallback | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment