Pregunta

Contexto

he estado programando en Java durante algunos años. Y atm estoy aprendiendo algo totalmente diferente: Clojure. Existe el problema de la expresión pueden ser resueltos mediante el uso de métodos múltiples mientras que en Java, necesitará algo así como el patrón de visitante o algo parecido.

La pregunta

He estado leyendo acerca de métodos múltiples y hacía bastante confundido con la diferencia real con la sobrecarga de métodos.

La única diferencia vi tan lejos que una multimethod no depende del tipo de tiempo de ejecución del objeto sobre el que se llama al método.

¿Fue útil?

Solución

Overloading is when two or more methods have the same name but different signature (different argument types, different number of arguments). Overloading is resolved statically, depending only on the static types of the arguments. (The interaction of overloading and overriding, in Java, for example, makes the story a little more complicated). Overloading resolves statically to a particular method signature. Then at runtime, dynamic dispatch will select the most appropriate method with that signature.

Multimethods are a collection of methods that have the same name, the same number of arguments, and overlapping type signatures. Whenever a call is made to a multimethod (using the name of the multimethod), all of the methods in the collection is considered as a possible candidate for dispatch. The precise candidate is chosen depending on the runtime types of the arguments – the most specific method is selected. The actual runtime types of all arguments are used to determine which one to run, which differs from traditional single dispatch in Java, where only the first argument (the target) of the method is used to determine which method body is run.

Otros consejos

As far a as my understanding goes:

Multimethods are a generalization of method polymorphism.

A multimethod consists of 2 parts

  1. A name

  2. A dispatch method: which will produce a dispatch value

Based on this dispatch value, the appropriate method will be chosen. Overloading is a special case of multimethods where the dispatch method will return the static type as a dispatch value

In general, the dispatch method can be anything. It can return other values than the type.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a cs.stackexchange
scroll top