Besides the cosmetic differences, what is the difference between key and optional these:
(defun play (&key now)
...)
(defun play (&optional now)
...)
As i understand it, in both cases:
- they are optional
- neither returns a list to the function like &rest
&optional
Optional arguments are, hmm, optional. You can omit them and they may have default values. They need to be provided in order.
Above omits the output stream, since it is optional and has a default value.
Above provides a stream, since we don't want to use the default value.
Thus the following three call variations are possible:
&key
Keyword arguments are named, optional and can be provided in any order:
Now all the following five call variations are possible:
One can provide the keyword/value pairs in any order, omit some or omit all.
Benefits of keyword arguments
Thus keyword arguments give a lot of flexibility:
The price to pay: keyword arguments may make some calls slower than calls with fixed parameter lists.
When to use keyword parameters?
Developers will write functions, macros, ... with keyword parameters when there are multiple (even many) optional arguments without clear order preference. The more readable code is an added advantages.