Skip to content

Instantly share code, notes, and snippets.

@scf37
Created September 13, 2017 19:45
Show Gist options
  • Save scf37/5ac5019a3685dc2a0956e70b89c77e7a to your computer and use it in GitHub Desktop.
Save scf37/5ac5019a3685dc2a0956e70b89c77e7a to your computer and use it in GitHub Desktop.
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