Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active August 29, 2015 14:14
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 frgomes/bde451a058efef6448af to your computer and use it in GitHub Desktop.
Save frgomes/bde451a058efef6448af to your computer and use it in GitHub Desktop.
Scala - Sample usage of fold() instead of getOrElse()
// This sample demonstrates how fold(...) can be employed instead
// of getOrElse(...) in cases you need to process the value of an
// Option.
def informTaxDue(tax: Option[Float]) : String =
tax.fold("not declared") {
v: Float =>
if(v==0.0) "nothing to pay" else s"tax due is ${v}"
}
println( informTaxDue(None:Option[Float]) )
// prints "not declared"
println( informTaxDue(Option(0.0)) )
// prints "nothing to pay"
println( informTaxDue(Option(250.78)) )
// prints "tax due is 250.78"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment