Defmulti vs defprotocol?

It seems that both can be used to define functions that you can implement later, with different data types. AFAIK, the main difference is that defmulti works on maps, and defprotocol works on records.

What other differences are there? What are the benefits of using one over the other?

+4
source share
2 answers

Short version: defmulti much more flexible and generic, while defprotocol works better.

A slightly longer version:

defprotocol supports sending by type, which is similar to polymorphism in most major programming languages.

defmulti is a more general mechanism where you can send things other than one type. This flexibility is ensured by a penalty for performance.

More about protocols

More on multimethods

+10
source

Just adding to cover motivation, the corvuscorax answer covers the original question.

Initially, Clojure had only multimethods , and very early in the course of many thoughts there was an assembly of abstraction that could handle all cases very well and would not force people to structure their abstractions around the limitation of abstractions offered by the language.

How Clojure matured the desire to create the “clojure in clojure” required abstractions, which, at least in theory, are capable of creating some kind of bytecode that can be created by java and, therefore, the need for protocols , sending abstraction, which is closer to native Java.
Clojure has the strong idea of ​​“hugging your platform,” and the protocols are very well suited for this thinking.

+5
source

Source: https://habr.com/ru/post/1391609/


All Articles