Scala logic switch logic what other words in this code mean
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."
}
println(res)
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).
source to share