Scala logic switch logic what other words in this code mean

days match {
  case firstDay :: otherDays =>
    println("The first day of the week is: " + firstDay)
  case List() =>
    println("There don't seem to be any week days.")


In this code, what does "otherDays" mean? How do you understand this wiring closet logic?



source to share

2 answers

It is not the switch itself. In Scala, it is called pattern matching. days

maps to the two examples in your example. Although you didn't specify the type of the variable days

, it probably is List


If your list is not empty, it will match the first case: case firstDay :: otherDays

and will be deconstructed or unapplied to two variables head :: tail

. The operator ::

"creates a list by adding the item on the left to the list on the right. In your case, it was used to deconstruct the list. Essentially it looks like this: ::(head, tail)

which becomes a call ::.unapply(selector)

where ::

is an object, and unapply

has a signature like this:

def unapply[A](value: List[A]): Option[(A, List[A])]


So, the end unapply

is called on your list, returning Some

its head and tail if the list is not empty, or None

otherwise. Scala will automatically convert Option

to match the correct one case

according to your template.

Note that the type of the result of this expression Unit

is not very FP style. You can change it to:

val res =
days match {
  case firstDay :: otherDays =>
    "The first day of the week is: " + firstDay
  case List() =>
    "There don't seem to be any week days."


to be more functional. In this case, the return type will be String

, and you delay the side effects until the very end (much more testable).



It looks like days

it's List

days. The first case is list destructuring, where firstDay

is the head of the list and otherDays

is the tail or "rest" of the list.

The first case will match on any non-empty list, whereas the second case will match on an empty list.



All Articles