-
-
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).
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
// --- 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