Created
September 13, 2017 19:45
-
-
Save scf37/5ac5019a3685dc2a0956e70b89c77e7a to your computer and use it in GitHub Desktop.
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 EitherUtils { | |
implicit class EitherWithFilter[L, R](either: Either[L, R]) { | |
def withFilter(filter: R => Boolean): Either[L, R] = either.flatMap { rv => | |
try { | |
if (filter(rv)) Right(rv) else throw new RuntimeException("withFilter returned false") | |
} catch { | |
case e: EitherException[_] => Left(e.value.asInstanceOf[L]) | |
} | |
} | |
} | |
case class EitherCondition(condition: Boolean) { | |
def thenFailWith[T](error: => T): Boolean = | |
if (condition) throw new EitherException[T](error) | |
else true | |
} | |
private[EitherUtils] case class EitherException[T] (value: T) extends RuntimeException with NoStackTrace | |
implicit def toDataCondition(cond: Boolean): EitherCondition = EitherCondition(cond) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment