Last active
October 4, 2016 06:40
-
-
Save jruusu/6b17a27dba89191e89f4e1b34a141ca2 to your computer and use it in GitHub Desktop.
Scala: Boolean to Option
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
// By extending Boolean | |
// See: http://docs.scala-lang.org/overviews/core/value-classes.html#extension-methods | |
implicit class PimpedBoolean(val self: Boolean) { | |
def toOption[T](x: => T): Option[T] = if (self) Some(x) else None | |
} | |
true toOption "foox" // => Some(foox) | |
true toOption { | |
println("garglex") | |
"foox" | |
} // => Some(foox) | |
false toOption "fooz" // => None | |
false toOption { | |
println("garglez") | |
"fooz" | |
} // => None | |
// By filtering | |
val a = true | |
val b = false | |
Some("fred") filter (_ => a) // => Some(fred) | |
Some("barney") filter (_ => b) // => None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment