As a brief note today, here’s an example of the Scala 3 “Dotty” if/then/else-if/else syntax, as used in a function:
def compare(a: Int, b: Int): Int = if a < b -1 else if a == b 0 else 1
Using `then` with if/else
You can also use the
then keyword after your
if expressions, if you prefer:
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
If you want to see a somewhat larger example of Dotty source code than I’ve shown before, I just took a little time to convert a small Scala 2 project over to the new/current Dotty syntax (i.e., the Dotty syntax supported by the Dotty 0.21 release, circa January, 2020).
I’ve written this before, but when I saw this “pseudocode to Scala code” example in the book Functional Thinking, I thought it was worth mentioning again: If you have trouble grokking the Scala
map method, think of it as being named
transform instead. It transforms an input collection to an output collection, based on the algorithm you supply.
For those coming from the OOP world, I think “transform” is a better word because it is more meaningful, at least initially.
Scala 2.13 introduced two new “chaining operations” named
tap. Here’s a quick look at how they work, plus a little extra fun at the end.
Back in 2016, Li Haoyi put together this nice article titled, Benchmarking Scala Collections.
I was working on some new code for my functional programming in Scala book today. At one point I thought everything looked okay, so I decided to generate some Scaladoc to see what certain things looked like. Admittedly I’m a bit tired today, but when I saw that Scaladoc I thought, “Good grief, Al, what sort of ugly API have you created?”
For some reason, seeing the Scaladoc helped me easily see the errors of my way. I’m not sure that I’ll ever be promoting a “Scaladoc-driven API design” process, but seeing the Scaladoc generated from my code sure helped today.
~ a note from August 30, 2017
I normally don’t like to have sales on my books, but the short story is that the PDF version of Functional Programming, Simplified is currently on sale for $15.
Scala problem: You want to be able to read configuration files that are written in the Lightbend “Config” file format.Back to top
Lightbend — initially named Typesafe — created a configuration file format named HOCON, which stands for, “Human-Optimized Config Object Notation.” As an example, a small HOCON configuration file looks like this: