I was reading the Input and Output chapter of Learn You a Haskell for Great Good when I saw that the author wrote this code:
dispatch :: [(String, [String] -> IO ())] dispatch = [ ("add", add) , ("view", view) , ("remove", remove) ]
What that Haskell code does is to create an “association map” that points from (a) the String
on the left to (b) the function reference on the right. That is, in this code:
("add", add)
the string "add"
is the key in the map, and add
is the name of a function that’s defined somewhere else on that page.
In Scala the equivalent association map code looks like this:
val dispatch = Map( "add" -> add, "view" -> view, "remove" -> remove )
You can also define it explicitly like this, if you prefer:
val dispatch: Map[String, () => Any] = Map( "add" -> add, "view" -> view, "remove" -> remove )
I haven’t explored this too much yet, I just wanted to see if it could be done, and if so, what special syntax might be required. But as you can see, it’s pretty straightforward.
The complete Scala source code
If you want to experiment with this some yourself, this is the test object I created when taking a look at this:
object FunctionInMapTest extends App { def add = ??? def view = ??? def remove = ??? val dispatch1 = Map( "add" -> add, "view" -> view, "remove" -> remove ) val dispatch2: Map[String, () => Any] = Map( "add" -> add, "view" -> view, "remove" -> remove ) }
If you put that code into your favorite IDE you’ll see that it all compiles just fine.
I like this example because it shows another thing you can do when you treat a function just like any other value in your programming language.
(Unfortunately this approach gets much more difficult when the functions you want to store in the Map
have different function signatures.)
Another example of storing functions in a Scala Map
While I’m in this neighborhood, here’s another example that shows how to store Scala methods and functions in a Map
:
def add(i: Int, j: Int) = i + j def multiply(i: Int, j: Int) = i * j // store the functions/methods in a Map val functions = Map( "add" -> add, "multiply" -> multiply ) // extract a function and then use it val f = functions("add") f(2, 2) // 4
If you ever want to store Scala methods and functions in a Map
, I hope these examples are helpful.