What is the scala idiom for writing a function which takes a huge number of key/value pair arguments which the caller can usually omit any/most/some of?
In lisp languages this is done with keyword arguments (common lisp and also clojure). For example I can define the function to take any of the keys :a
, :b
, :c
, :d
,:e
, :f
, :g
, :h
and the types associated with any of the arguments can be specified if desired. Then when the function is called the caller can specify any or all of the keys and their associated values.
I know that scala does not support this exact thing, but there must be some way to achieve the same effect?
The case I have is that I have a gnuPlot
function which takes a descriptor for a set of curves to plot. But a gnu-plot plot has lots and lots and lots of options for log axes, soft/hard grid, boundaries, line or scatter plot, axis labels, etc etc etc. I don’t want the caller of gnuPlot
to have to specify all of these, only the ones he cares about.
The lisp code call site might look like the following:
(gnu-plot data :x-log t :y-log nil :label-font "Helvetica" :x-min 100.0 :line-width 3)
(gnu-plot data :y-max 1000.0 :line-color "green")
I considered just having a second argument which is a Map[String,Any]
, but I’ve never worked with Any
type in Scala. I would have to do manual type checking on the expected types. I don’t even know whether it is possible.
I also considered creating a case class called gnuPlotOptions whose member variables are the supported options and are declared with the correct types, but I don’t know how to instantiate a case class only specifying some of the arguments in any order.
Perhaps there is a much better way?