One thing I increasingly love about Scala is this: functions are objects, and for many common objects it is true that objects are functions as well. Some examples are arrays, lists, maps etc. For example, lets say we have a map from numeric characters to English words corresponding to these numbers:
val n2s = Map( '0' -> "zero", '1' -> "one", '2' -> "two", '3' -> "three", '4' -> "four", '5' -> "five", '6' -> "six", '7' -> "seven", '8' -> "eight", '9' -> "nine")
This map moonlights as (okay, okay, “inherits from”) a function of the type
(Char => String) and you can pass it where such a function is expected as parameter, like here:
Quick explanation for those new to Scala:
Stringis also a
Seq[Char]in Scala land, and the
mapmethod applies a function of
Char => B(where
Bis any type) to each element in the sequence, thus producing a new
- we pass our map
n2sto this function, which means we will map the
- that sequence is then turned into a single
mkString(and specifying space as the separator between elements)
This function is just an example, it probably isn’t actually useful for anything. I just saw something like it in Python and thought I’d try to make the same program in Scala before realizing that it didn’t do anything really interesting (like converting 123 into “one hundred twenty-three” instead of “one two three”).
Another awesome thing about functions in Scala are partial functions, which are functions taking a single argument that are defined only for some argument values (the domain of the function). Map is also a partial function — defined only for the keys it contains — and pattern matching, which is a very important part of Scala, is related to partial functions as well. I won’t go into more detail in this post, but Doug Pardee has written a more in-depth article about functions in Scala.