I originally wrote a long introduction to this article about Scala Options, but I decided to keep that introduction for a future second article in this series. For this article I’ll just say:
- idiomatic Scala code involves never using null values
- because you never use nulls, it’s important for you to become an expert at using
- initially you may want to use match expressions to handle
- as you become more proficient with Scala and Options, you’ll find that match expressions tend to be verbose
- becoming proficient with higher-order functions (HOFs) like
fold, and many others are the cure for that verbosity
Here’s a little Scala 3 (Dotty)
enum match/case expression example:
This scala-lang.org documentation page shares a good reason to use “sealed” traits and classes: When you created sealed traits, the compiler can easily tell all of the subtypes of your class or trait, and as just one benefit, you don’t need to add a default, “catch-all” case in your Scala
Scala FAQ: How can I use regular expression (regex) pattern matching in a
match expression (a Scala match/case expression)?
As I wrote in my Scala sed class post earlier today, Jon Pretty’s Kaleidoscope project lets you use string pattern-matching code in Scala
match expressions. This enables regex pattern-matching code like this:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 20.6, “Scala best practice: How to use the Option/Some/None pattern.”Back to top
For a variety of reasons, including removing
null values from your Scala code, you want to use what I call the Option/Some/None pattern. Or, if you’re interested in a problem (exception) that occurred while processing code, you may want to return Try/Success/Failure from a method instead of Option/Some/None.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 20.4, “Scala best practice: Use match expressions and pattern matching.”Back to top
Match expressions (and pattern matching) are a major feature of the Scala programming language, and you want to see examples of the many ways to use them.Back to top
Match expressions (match/case statements) and pattern matching are a major feature of the Scala language. If you’re coming to Scala from Java, the most obvious uses are:Back to top
An interesting story on the Scala phrase, “flatMap that sh*t”, from SO.