Skip to content

Instantly share code, notes, and snippets.

@mancvso
Forked from joa/gist:5141649
Last active December 14, 2015 20:58
Show Gist options
  • Save mancvso/5147468 to your computer and use it in GitHub Desktop.
Save mancvso/5147468 to your computer and use it in GitHub Desktop.
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
}
trait Mammal
case object Cat extends Mammal
case object Dog extends Mammal
val uri = "/news/index.html"
val file = "index.html" when uri == "/" otherwise uri
val result = {println("eval when");Cat} when {println("eval cond");false} otherwise {println("eval otherwise");Dog}
/* --- output
eval cond
eval otherwise
result: Product with Serializable with Mammal = Dog
file: String = /news/index.html
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment