option

How to use higher-order functions with Option (instead of match expressions)

I originally wrote a long introduction to this article, but I decided to keep that introduction for the 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 to become an expert at using Option, Some, and None
  • initially you may want to use match expressions to handle Option values
  • 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 map, filter, fold, and many others are the cure for that verbosity

Given that background, the purpose of this article is to show how to use HOFs with Option values rather than match expressions.

Scala: A look at flatMap and map on Option

As a quick Scala tip, if you haven’t worked with the flatMap on an Option much, it can help to know that flatMap’s function should return an Option, which you can see in this REPL example:

scala> Some(1).flatMap{ i => Option(i) }
res0: Option[Int] = Some(1)

You can tell this by looking at the function signature in the scaladoc for the flatMap method on the Option class:

Creating a drop-down list in Play Framework 2.6

As a brief note to self before I delete this code, this is how you create a drop-down list in Play Framework 2.6:

@* adding 'size to helper.select creates a select/option area (single or multi-select) *@
@helper.select(
    form("category"),
    categories,
    'id -> "category",
    '_help -> "Select one, any one"
)

In that code, categories is passed into the Play template like this:

Functional error handling in Scala

Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have exceptions when you try to access servers that are down or files that are missing, so what can you do? This lesson demonstrates the techniques of functional error handling in Scala.

Scala: Handling nested Options with flatMap and for

Summary: In this article I show a couple of ways to extract information from optional fields in your Scala domain models. This example is a little contrived, but if you have a situation where one Option instance contains one or more other Options, this article may be helpful.

There are times when you’re creating your domain model when it makes sense to use optional fields in your case classes. For instance, when you model an Address, the “second street address” isn’t needed for all people, so making it an optional field makes sense:

How to use `curl` to get headers from a URL

Curl FAQ: How do I use curl to get the headers from a website URL?

Short answer: Use curl's -I option, like this:

$ curl -I URL

Here's a specific example, including a real URL and results: