Created
October 9, 2023 17:49
-
-
Save valdo404/94b5eca7fa885ca247aad6c35aabed36 to your computer and use it in GitHub Desktop.
test-recoverable
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
case class Recoverable[A](errors: Seq[Throwable], a: Option[A]) { | |
def map[B](f: A => B): Recoverable[B] = { | |
val b = a.map(f) | |
Recoverable(errors, b) | |
} | |
def flatMap[B](f: A => Recoverable[B]): | |
Recoverable[B] = { | |
val result: Option[Recoverable[B]] = a.map(f) | |
result match { | |
case Some (validated) => | |
validated.addErrors(errors) | |
case None => | |
this.addError(new Exception("Unrecoverable")).copy(a = Option.empty[B]) | |
} | |
} | |
def filter(f: A => Boolean): Recoverable[A] = { | |
val result = a.exists(f) | |
if(result) | |
this | |
else | |
addError(new Exception("Filtered: "+ result)). | |
copy(a = None) | |
} | |
def withFilter(f: A => Boolean) = filter(f) | |
def addError(e: Throwable) = copy(errors = errors.appended(e)) | |
def addErrors(e: Seq[Throwable]) = copy(errors = errors ++ e) | |
def recoverable: Boolean = a.isDefined | |
def orElse(recoverable: Recoverable[A]): Recoverable[A] = if(a.isDefined) this else recoverable | |
} | |
object Recoverable { | |
def just[A](a: A): Recoverable[A] = Recoverable[A](Seq(), Some(a)) | |
def unrecoverable[A](t: Throwable) = new Recoverable[A](Seq(t), None) | |
def recoverable[A](t: Throwable, a: A) = new Recoverable[A](Seq(t), Some(a)) | |
} | |
object MultiValidatedApp extends App { | |
private val value: Recoverable[Int] = for { | |
a <- Recoverable.just(1) | |
b <- Recoverable.just(2) | |
} yield (a + b) | |
private val value2: Recoverable[String] = for { | |
a <- Recoverable.just(1) | |
b <- Recoverable.just("2") | |
} yield (a.toString + b) | |
private val value3: Recoverable[String] = for { | |
a <- Recoverable.unrecoverable[Int](new Exception("blah")) | |
b <- Recoverable.just("2") | |
} yield (a.toString + b) | |
private val value4: Recoverable[String] = for { | |
a <- Recoverable.recoverable[Int](new Exception("blah"), 2) | |
b <- Recoverable.recoverable[Int](new Exception("blou"), 4) if(b == 4) | |
c <- Recoverable.just("2") | |
} yield (a + b + c) | |
private val value5: Recoverable[String] = for { | |
a <- Recoverable.recoverable[Int](new Exception("blah"), 2) | |
b <- Recoverable.unrecoverable[Int](new Exception("blou")) | |
c <- Recoverable.just("2") | |
} yield (a + b + c) | |
private val value6: Recoverable[Int] = | |
Recoverable.recoverable[Int](new Exception("blah"), 2).orElse( | |
Recoverable.unrecoverable[Int](new Exception("blou")) | |
).orElse(Recoverable.just(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment