Skip to content

Instantly share code, notes, and snippets.

@sam
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam/9765394 to your computer and use it in GitHub Desktop.
Save sam/9765394 to your computer and use it in GitHub Desktop.
Examples of using Booleans to filter optional values.
// Example values.
val applyTitle = true
val title = Some("This is my Title!")
// We want to map these values to Option[Option[String]]
// where Option[String] is our value, and the outer Option[_]
// is an indicator on wether we should later use the value or not.
//
// eg: We want to support three use-cases:
//
// * The value should be applied: Some(Some("This is my Title!"))
// * The value should be cleared: Some(None)
// * The value should not be modified: None
// Some examples below are condensed to one line where it seemed
// idiomatically appropriate (eg: how I would write it in actual code).
// BEGIN EXAMPLE 1
val example1 = applyTitle match {
case true => Some(title)
case false => None
}
// BEGIN EXAMPLE 2
val example2 = if(applyTitle) Some(title) else None
// You could inject newlines, but I feel like the indentation
// would feel more awkward than just condensing it to one line.
// BEGIN EXAMPLE 3
val example3 = Option(applyTitle) filter(identity) map(_ => title)
// Newlines would require leading .dot notation on the method calls, and
// I feel like the above reads better.
// BEGIN EXAMPLE 4
val example4 = Option(applyTitle) collect { case true => title }
// Of the one-liner functional examples I like this one is best.
// It also helps to flex a method that I feel like could be used more
// frequently if I trained myself better.
// BEGIN EXAMPLE 5
implicit class BooleanOption(value: Boolean) {
def collect[T](substitution: T): Option[T] = {
if(value)
Some(substitution)
else
None
}
}
val example5 = applyTitle collect title
// If I needed to perform this operation a dozen or more times this
// is the version I'd go with. Drop the implicit into a util package object
// and reuse whenever I feel like it.
//
// I called the method "map" at first, but I feel like "collect" actually
// reinforces the type signatures better. ie: If I "collect" a "true" value
// Some(substitution) is a reasonable expectation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment