DEV Community

Cover image for Overloading in Clojure
Marcos Henrique
Marcos Henrique

Posted on

Overloading in Clojure

Dear Atomic God, what is this ??? 🤯

Overload is the ability to define multiple properties, methods, or procedures in a class with the same name but different parameters.

You understood ?
Well, I'll be clearer.

If you create two procedures in your application with the same name and different parameters, you are using overhead.

You may be asking, "How can I create two procedures with the same name? How will I differentiate them?"

Smart boy/girl you!!!

You will differentiate the methods / procedures by the parameter list they will have, ie the methods/procedures/functions will have different parameters.

As in Clojure we use the functional paradigm is more how we can increase the arity of our function.

So... What is Arity? 🤔

In mathematics, an area of ​​function or operation is the number of arguments or operands taken.
The arity of a relation is the number of elements that compose as ordered n-tuples belonging to the relation.

After this brief introduction, hands on 😁

Let's suppose we have an array of names and we want to count how many elements we have in it without the famous length or count of another languages like javascript or c#.

(defn count  
   (count 0 elements)) ;First overload
  ([total elements]  
   (if (seq elements)  
     (recur (inc total) (next elements))  
     total))) ;Second overload

(println (count ["dylan" "inae" "leandro" "marcos"])) ;returns 4 
(println (count [])) ;returns 0
Enter fullscreen mode Exit fullscreen mode

Simple like this, just add your params and what you want to do into () and now you can implements many aritys in same function

seq➡ Implements a sequence, in the code above I implemented this to know if my array has elements, because if not this method returns null or nil in clojure

recur➡ Implements a otimized recursivity, prevents exceptions

inc➡ A method to sum 1 (like ++, value + 1 or (+ value 1) in clojure

next➡ Returns a seq of the items after the first. Calls seq on its
argument. If there are no more items, returns nil.

For today is what I have to share, until next time 🤓

Top comments (0)