Skip to content

Instantly share code, notes, and snippets.

@octonato
Last active December 23, 2016 21:16
Show Gist options
  • Save octonato/fc0c0000d699742c5831846dfe58b89e to your computer and use it in GitHub Desktop.
Save octonato/fc0c0000d699742c5831846dfe58b89e to your computer and use it in GitHub Desktop.
// some experiments for a 'if' replacement for situations where the
// 'else' branche is generified to None or Failure
import scala.util._
import scala.concurrent.Future
class When(cond: => Boolean) {
def apply[T](value: => T): Option[T] = WhenOption.when(cond)(value)
def some[T](value: => T): Option[T] = WhenOption.when(cond)(value)
def success[T](value: => T): Try[T] = WhenTry.when(cond)(value)
def failure[T](ex: => Throwable): Try[Boolean] = WhenTry.when(cond).failure(ex)
def successAsync[T](value: => T): Future[T] = WhenFuture.when(cond)(value)
def failureAsync[T](ex: => Throwable): Future[Boolean] = WhenFuture.when(cond).failure(ex)
}
object When {
def when(cond: => Boolean): When = new When(cond)
def whenNot(cond: => Boolean): When = new When(!cond)
}
class WhenOption(cond: => Boolean) {
def apply[T](value: => T): Option[T] = some(value)
def some[T](value: => T): Option[T] = if (cond) Some(value) else None
}
object WhenOption {
def when(cond: => Boolean): WhenOption = new WhenOption(cond)
def whenNot(cond: => Boolean): WhenOption = new WhenOption(!cond)
}
class WhenTry(cond: => Boolean) {
def apply[T](value: => T): Try[T] = success(value)
def success[T](value: => T): Try[T] =
if (cond) Success(value)
else Failure(new RuntimeException("condition evaluated to false"))
def failure(ex: => Throwable): Try[Boolean] = {
val evaluated = cond
if (evaluated) Failure(ex)
else Success(!evaluated)
}
}
object WhenTry {
def when(cond: => Boolean): WhenTry = new WhenTry(cond)
def whenNot(cond: => Boolean): WhenTry = new WhenTry(!cond)
}
class WhenFuture(cond: => Boolean) {
def apply[T](value: => T): Future[T] = success(value)
def success[T](value: => T): Future[T] =
Future.fromTry(WhenTry.when(cond).success(value))
def failure(ex: => Throwable): Future[Boolean] =
Future.fromTry(WhenTry.when(cond).failure(ex))
}
object WhenFuture {
def when(cond: => Boolean): WhenFuture = new WhenFuture(cond)
def whenNot(cond: => Boolean): WhenFuture = new WhenFuture(!cond)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment