This is a pretty silly mistake that I was making, but it was really confusing me for a minute. I was forgetting to wrap the arguments and function body within a set of parens when using multi-arity functions in ClojureScript. Let me know you what I mean.
The "arity" of a function refers to the number of arguments that it accepts. In Clojure, we can have multiple function bodies, and each one corresponds to a specific number of arguments. (note: very similar features are present in other programming languages and are sometimes referred to as "function overloading").
Here's some code I was writing earlier today. I wanted to create a function named "derp" that returned "hey, you!" if it received one argument or "hey, y'all!" if it receives two arguments. However, I was surprised to see that no matters how many arguments I passed in, it was always returning, "hey you!".
The problem with the above code is that I forgot to wrap the different arities in another set of parentheses. When Clojure runs this code it sees it as a single arity (that takes one argument) with a function body that is just a series of three expressions. The last expression is the "hey y'all" string, and so it makes sense that this function would always return that string.
The correct way to write this code would be to use those parens! Wrap each argument vector and function body in another set of parens to let Clojure know you want to use a multi-arity function, like so:
The posts on this site are written and maintained by Jim Lynch. About Jim...