Cubic
Cubic

Reputation: 15673

Variable number AND keyword arguments?

Other than something like

(fn [& {:keys [more the-rest]}] ,,,)

Is there a way to use variable numbers of arguments and keyword arguments at the same time, e.g.

(my-function arg1 arg2 some-other-args :opt1 opt1 :opt2 opt2)

?

Upvotes: 1

Views: 171

Answers (1)

mikera
mikera

Reputation: 106351

You can define your function to take arguments in whatever way you like, but the issue you will run into is how to tell the difference between ambiguous situations like:

(my-function arg1 arg2 arg3 arg4)
(my-function arg1 arg2 key1 val1)

In order to tell the difference, you'll need to write code to examine the parameters at runtime (for example checking whether the third parameter is a keyword or not). This will get ugly pretty fast.

Consequently, I wouldn't recommend going down this route. Alternatives to consider:

  • Simplify your functions. If you have this many arguments, it could mean that you have "complected" too much into a single function.
  • Pass all key/value arguments as a single map

Upvotes: 2

Related Questions