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:
n.toString.map(n2s).mkString(" ")
Quick explanation for those new to Scala:
n.toStringconvertsnto itsStringrepresentation- a
Stringis also aSeq[Char]in Scala land, and themapmethod applies a function ofChar => B(whereBis any type) to each element in the sequence, thus producing a newSeq[B] - we pass our map
n2sto this function, which means we will map theSeq[Char]to aSeq[String] - that sequence is then turned into a single
StringusingmkString(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.
March 12, 2008 at 12:57 pm |
[...] (functions == objects) => awesome! « Villane [...]
November 26, 2008 at 11:09 am |
The first scala-code I saw that exploited the fact that functions are objects and hence classes can extend functions was in Szeigers excellent parsing series: http://szeiger.de/blog/2008/07/27/formal-language-processing-in-scala-part-1/
I love the simplicity of your example. Perhaps it would be even easier to understand if n had a value in example or leave out n entirely:
“1234567″.map(n2s).mkString(” “)
That’s a minor detail that didn’t keep me from sharing your excitement with this feature of Scala. I did not know that maps are also functions, I’ll have to keep my eye out for hidden treats like this in the future.
Thanks for posting this!
/J