Welcome! Please see the About page for a little more info on how this works.

0 votes
in Multimethods by

When two multimethods have the same dispatch value, what is the method of resolution?

In order to answer this questions, I experimented by creating four files (core.cljs, a.clj, b.clj, interface.clj [where `defmulti` is defined]), implemented some methods in a and b namespace with the same dispatch value.

Finally in core namespace, I required a and b, and observed the resolution was given by the order of the import of the namespace.

However, in a bigger project, the order did not have an impact: I was overriding a multimethod in a library, and I suspect the resolution was made with respect to the folder in the classpath.

Can anyone confirm or infirm my hypothesis?

Best regards,
David

1 Answer

+1 vote
by

Each "defmulti" knows at-most-one method with any particular dispatch value. If a second "defmethod" comes along, it replaces the first. This is a cornerstone of REPL-based development.

On the other hand, there is some interesting work behind-the-scenes to dispatch a multimethod call in cases when the dispatch function returns a value that is related (by the relevant hierarchy) to more than one method's dispatch value. In that case, see prefer-method.

by
In this case, how do we know the order of defintion the multimethods?

Say a library deps defines a methods for dispatch value `a`, and our custom code base override the method for the same dispatch value, which one will be preceed?
by
That's a sorry state of affairs!  Perhaps you could `eval` your overriding defmulti after you feel certain that the library has loaded all the code that it will ever load.  But that is a crude and brittle solution.  Fork the library and make it properly configurable?
...