Skip to content

Instantly share code, notes, and snippets.

View mancvso's full-sized avatar
🏠
Working from home

Alejandro Vidal Castillo mancvso

🏠
Working from home
View GitHub Profile
@mancvso
mancvso / WhenUnlessOtherwise.scala
Last active December 14, 2015 20:58 — forked from joa/gist:5141649
when / unless / otherwise implementation in Scala with some Implicit Value Classes and call by name (deferred evaluation only when necessary).
// --- Shorter with Option[T] --- //
implicit class WhenUnless[T](x: => T) {
lazy val xx = x
def when(cond: => Boolean):Option[T] = if(cond) Some(xx) else None
def unless(cond: => Boolean):Option[T] = if(cond) None else Some(xx)
}
implicit class Otherwise[+T](val x: Option[T]) extends AnyVal {
def otherwise[S >: T](z: => S):S = if(x.isDefined) x.get else z //could not use getOrElse