Multiple dispatch or multimethods is a feature of some
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s in which a
function
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-oriente ...
or
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
can be
dynamically dispatched based on the
run-time (dynamic) type or, in the more general case, some other attribute of more than one of its
arguments
An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialectic ...
. This is a generalization of
single-dispatch polymorphism where a function or method call is dynamically dispatched based on the derived type of the object on which the method has been called. Multiple dispatch routes the dynamic dispatch to the implementing function or method using the combined characteristics of one or more arguments.
Understanding dispatch
Developers of computer software typically organize
source code
In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
into named blocks variously called
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
s, procedures, subprograms, functions, or methods. The code in the function is executed by ''calling'' it – executing a piece of code that references its ''name''. This transfers control temporarily to the called function; when the function's execution has completed, control is typically transferred back to the instruction in the ''caller'' that follows the reference.
Function names are usually selected so as to be descriptive of the function's purpose. It is sometimes desirable to give several functions the same name, often because they perform conceptually similar tasks, but operate on different types of input data. In such cases, the name reference at the function call site is not sufficient for identifying the block of code to be executed. Instead, the number and type of the arguments to the function call are also used to select among several function implementations.
In more conventional, i.e.,
single-dispatch object-oriented programming languages, when invoking a method (''sending a message'' in
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
, ''calling a member function'' in
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
), one of its arguments is treated specially and used to determine which of the (potentially many) classes of methods of that name is to be applied. In many languages, the ''special'' argument is indicated syntactically; for example, a number of programming languages put the special argument before a dot in making a method call:
special.method(other, arguments, here)
, so that
lion.sound()
would produce a roar, whereas
sparrow.sound()
would produce a chirp.
In contrast, in languages with multiple dispatch, the selected method is simply the one whose arguments match the number and type of the function call. There is no ''special'' argument that ''owns'' the function/method carried out in a particular call.
The
Common Lisp Object System
The Common Lisp Object System (CLOS) is the facility for object-oriented programming which is part of ANSI Common Lisp. CLOS is a powerful dynamic object system which differs radically from the OOP facilities found in more static languages such as ...
(CLOS) is an early and well-known example of multiple dispatch. Another notable example of the use of multiple dispatch is the
Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
programming language.
Data types
When working with languages that can discriminate
data type
In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
s at
compile time
In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled.
The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
, selecting among the alternatives can occur then. The act of creating such alternative functions for compile time selection is usually referred to as
overloading a function.
In programming languages that defer data type identification until run time (i.e.,
late binding
In computing, late binding or dynamic linkage—though not an identical process to Dynamic linker, dynamically linking imported code Library (computing), libraries—is a computer programming mechanism in which the Method (computer programming), ...
), selection among alternative functions must occur then, based on the dynamically determined types of function arguments. Functions whose alternative implementations are selected in this manner are referred to most generally as ''multimethods''.
There is some run-time cost associated with dynamically dispatching function calls. In some languages, the distinction between overloading and multimethods can be blurred, with the compiler determining whether compile time selection can be applied to a given function call, or whether slower run time dispatch is needed.
Use in practice
To estimate how often multiple dispatch is used in practice, Muschevici et al.
studied programs that use dynamic dispatch. They analyzed nine applications, mostly compilers, written in six different languages:
Common Lisp Object System
The Common Lisp Object System (CLOS) is the facility for object-oriented programming which is part of ANSI Common Lisp. CLOS is a powerful dynamic object system which differs radically from the OOP facilities found in more static languages such as ...
,
Dylan,
Cecil
Cecil may refer to:
People with the name
* Cecil (given name), a given name (including a list of people and fictional characters with the name)
* Cecil (surname), a surname (including a list of people with the name)
Places Canada
*Cecil, Alberta, ...
, MultiJava, Diesel, and Nice. Their results show that 13–32% of generic functions use the dynamic type of one argument, while 2.7–6.5% of them use the dynamic type of multiple arguments. The remaining 65–93% of generic functions have one concrete method (overrider), and thus are not considered to use the dynamic types of their arguments. Further, the study reports that 2–20% of generic functions had two and 3–6% had three concrete function implementations. The numbers decrease rapidly for functions with more concrete overriders.
Multiple dispatch is used much more heavily in
Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
, where multiple dispatch was a central design concept from the origin of the language: collecting the same statistics as Muschevici on the average number of methods per generic function, it was found that the Julia
standard library
In computer programming, a standard library is the library made available across implementations of a programming language. These libraries are conventionally described in programming language specifications; however, contents of a language's as ...
uses more than double the amount of overloading than in the other languages analyzed by Muschevici, and more than 10 times in the case of
binary operators
In mathematics, a binary operation or dyadic operation is a rule for combining two elements (called operands) to produce another element. More formally, a binary operation is an operation of arity two.
More specifically, an internal binary ope ...
.
[
The data from these papers is summarized in the following table, where the dispatch ratio ]DR
is the average number of methods per generic function; the choice ratio CR
is the mean of the square of the number of methods (to better measure the frequency of functions with a large number of methods);[ and the degree of specialization ]DoS
is the average number of type-specialized arguments per method (i.e., the number of arguments that are dispatched on):
Theory
The theory of multiple dispatching languages was first developed by Castagna et al., by defining a model for overloaded functions with late binding
In computing, late binding or dynamic linkage—though not an identical process to Dynamic linker, dynamically linking imported code Library (computing), libraries—is a computer programming mechanism in which the Method (computer programming), ...
. It yielded the first formalization of the problem of covariance and contravariance of object-oriented languages and a solution to the problem of binary methods.
Examples
Distinguishing multiple and single dispatch may be made clearer by an example. Imagine a game that has, among its (user-visible) objects, spaceships and asteroids. When two objects collide, the program may need to do different things according to what has just hit what.
Languages with built-in multiple dispatch
C#
C# introduced support for dynamic multimethods in version 4 (April 2010) using the 'dynamic' keyword. The following example demonstrates multimethods. Like many other statically-typed languages, C# also supports static method overloading. Microsoft expects that developers will choose static typing over dynamic typing in most scenarios. The 'dynamic' keyword supports interoperability with COM objects and dynamically-typed .NET languages.
The example below uses features introduced in C# 9 and C# 10.
using static ColliderLibrary;
Console.WriteLine(Collide(new Asteroid(101), new Spaceship(300)));
Console.WriteLine(Collide(new Asteroid(10), new Spaceship(10)));
Console.WriteLine(Collide(new Spaceship(101), new Spaceship(10)));
string Collide(SpaceObject x, SpaceObject y) =>
x.Size > 100 && y.Size > 100
? "Big boom!"
: CollideWith(x as dynamic, y as dynamic); // Dynamic dispatch to CollideWith method
class ColliderLibrary
record SpaceObject(int Size);
record Asteroid(int Size) : SpaceObject(Size);
record Spaceship(int Size) : SpaceObject(Size);
Output:
Big boom!
a/s
s/s
Groovy
Groovy
''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context.
History
The ...
is a general purpose Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
compatible/interusable JVM
A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describes ...
language, which, contrary to Java, uses late binding / multiple dispatch.
/*
Groovy implementation of C# example above
Late binding works the same when using non-static methods or compiling class/methods statically
(@CompileStatic annotation)
*/
class Program
class Collider
class SpaceObject
@InheritConstructors class Asteroid extends SpaceObject
@InheritConstructors class Spaceship extends SpaceObject
Common Lisp
In a language with multiple dispatch, such as Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
, it might look more like this (Common Lisp example shown):
(defmethod collide-with ((x asteroid) (y asteroid))
;; deal with asteroid hitting asteroid
)
(defmethod collide-with ((x asteroid) (y spaceship))
;; deal with asteroid hitting spaceship
)
(defmethod collide-with ((x spaceship) (y asteroid))
;; deal with spaceship hitting asteroid
)
(defmethod collide-with ((x spaceship) (y spaceship))
;; deal with spaceship hitting spaceship
)
and similarly for the other methods. Explicit testing and "dynamic casting" are not used.
In the presence of multiple dispatch, the traditional idea of methods as being defined in classes and contained in objects becomes less appealing—each ''collide-with'' method above is attached to two different classes, not one. Hence, the special syntax for method invocation generally disappears, so that method invocation looks exactly like ordinary function invocation, and methods are grouped not in classes but in generic function
In computer programming, a generic function is a function defined for polymorphism.
In statically typed languages
In statically typed languages (such as C++ and Java), the term ''generic functions'' refers to a mechanism for ''compile-time pol ...
s.
Julia
Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
has built-in multiple dispatch, and it is central to the language design. The Julia version of the example above might look like:
abstract type SpaceObject end
struct Asteroid <: SpaceObject
size::Int
end
struct Spaceship <: SpaceObject
size::Int
end
collide_with(::Asteroid, ::Spaceship) = "a/s"
collide_with(::Spaceship, ::Asteroid) = "s/a"
collide_with(::Spaceship, ::Spaceship) = "s/s"
collide_with(::Asteroid, ::Asteroid) = "a/a"
collide(x::SpaceObject, y::SpaceObject) = (x.size > 100 && y.size > 100) ? "Big boom!" : collide_with(x, y)
Output:
julia> collide(Asteroid(101), Spaceship(300))
"Big boom!"
julia> collide(Asteroid(10), Spaceship(10))
"a/s"
julia> collide(Spaceship(101), Spaceship(10))
"s/s"
Raku
Raku, like Perl, uses proven ideas from other languages, and type systems have shown themselves to offer compelling advantages in compiler-side code analysis and powerful user-side semantics via multiple dispatch.
It has both multimethods, and multisubs. Since most operators are subroutines, it also has multiple dispatched operators.
Along with the usual type constraints, it also has ''where'' constraints that allow making very specialized subroutines.
subset Mass of Real where 0 ^..^ Inf;
role Stellar-Object
class Asteroid does Stellar-Object
class Spaceship does Stellar-Object
my Str @destroyed = < obliterated destroyed mangled >;
my Str @damaged = « damaged 'collided with' 'was damaged by' »;
# We add multi candidates to the numeric comparison operators because we are comparing them numerically,
# but makes no sense to have the objects coerce to a Numeric type.
# ( If they did coerce we wouldn't necessarily need to add these operators. )
# We could have also defined entirely new operators this same way.
multi sub infix:« <=> » ( Stellar-Object:D $a, Stellar-Object:D $b )
multi sub infix:« < » ( Stellar-Object:D $a, Stellar-Object:D $b )
multi sub infix:« > » ( Stellar-Object:D $a, Stellar-Object:D $b )
multi sub infix:« » ( Stellar-Object:D $a, Stellar-Object:D $b )
# Define a new multi dispatcher, and add some type constraints to the parameters.
# If we didn't define it we would have gotten a generic one that didn't have constraints.
proto sub collide ( Stellar-Object:D $, Stellar-Object:D $ )
# No need to repeat the types here since they are the same as the prototype.
# The 'where' constraint technically only applies to $b not the whole signature.
# Note that the 'where' constraint uses the `<` operator candidate we added earlier.
multi sub collide ( $a, $b where $a < $b )
multi sub collide ( $a, $b where $a > $b )
# This has to be after the first two because the other ones
# have 'where' constraints, which get checked in the
# order the subs were written. ( This one would always match. )
multi sub collide ( $a, $b )
# The following two candidates can be anywhere after the proto,
# because they have more specialized types than the preceding three.
# If the ships have unequal mass one of the first two candidates gets called instead.
multi sub collide ( Spaceship $a, Spaceship $b where $a $b )
# You can unpack the attributes into variables within the signature.
# You could even have a constraint on them `(:mass($a) where 10)`.
multi sub collide ( Asteroid $ (:mass($a)), Asteroid $ (:mass($b)) )
my Spaceship $Enterprise .= new(:mass(1),:name('The Enterprise'));
collide Asteroid.new(:mass(.1)), $Enterprise;
collide $Enterprise, Spaceship.new(:mass(.1));
collide $Enterprise, Asteroid.new(:mass(1));
collide $Enterprise, Spaceship.new(:mass(1));
collide Asteroid.new(:mass(10)), Asteroid.new(:mass(5));
Extending languages with multiple-dispatch libraries
JavaScript
In languages that do not support multiple dispatch at the language definition or syntactic level, it is often possible to add multiple dispatch using a library
A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vir ...
extension. JavaScript and TypeScript do not support multimethods at the syntax level, but it is possible to add multiple dispatch via a library. For example, the ''multimethod package''[@arrows/multimethod](_blank)
Multiple dispatch in JavaScript/TypeScript with configurable dispatch resolution by Maciej Cąderek. provides an implementation of multiple dispatch, generic functions.
Dynamically-typed version in JavaScript:
import from '@arrows/multimethod'
class Asteroid
class Spaceship
const collideWith = multi(
method( steroid, Asteroid (x, y) => ),
method( steroid, Spaceship (x, y) => ),
method( paceship, Asteroid (x, y) => ),
method( paceship, Spaceship (x, y) => ),
)
Statically-typed version in TypeScript:
import from '@arrows/multimethod'
class Asteroid
class Spaceship
type CollideWith = Multi &
const collideWith: CollideWith = multi(
method( steroid, Asteroid (x, y) => ),
method( steroid, Spaceship (x, y) => ),
method( paceship, Asteroid (x, y) => ),
method( paceship, Spaceship (x, y) => ),
)
Python
Multiple dispatch can be added to Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
using a library
A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vir ...
extension. For example, using the module ''multimethod.py'' and also with the module ''multimethods.py''[multimethods.py](_blank)
, Multiple dispatch in Python with configurable dispatch resolution by David Mertz, et al. which provides CLOS-style multimethods for Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
without changing the underlying syntax or keywords of the language.
from multimethods import Dispatch
from game_objects import Asteroid, Spaceship
from game_behaviors import as_func, ss_func, sa_func
collide = Dispatch()
collide.add_rule((Asteroid, Spaceship), as_func)
collide.add_rule((Spaceship, Spaceship), ss_func)
collide.add_rule((Spaceship, Asteroid), sa_func)
def aa_func(a, b):
"""Behavior when asteroid hits asteroid."""
# ...define new behavior...
collide.add_rule((Asteroid, Asteroid), aa_func)
# ...later...
collide(thing1, thing2)
Functionally, this is very similar to the CLOS example, but the syntax is conventional Python.
Using Python 2.4 decorators, Guido van Rossum
Guido van Rossum (; born 31 January 1956) is a Dutch programmer best known as the creator of the Python programming language, for which he was the " benevolent dictator for life" (BDFL) until he stepped down from the position on 12 July 20 ...
produced a sample implementation of multimethods with a simplified syntax:
@multimethod(Asteroid, Asteroid)
def collide(a, b):
"""Behavior when asteroid hits a asteroid."""
# ...define new behavior...
@multimethod(Asteroid, Spaceship)
def collide(a, b):
"""Behavior when asteroid hits a spaceship."""
# ...define new behavior...
# ... define other multimethod rules ...
and then it goes on to define the multimethod decorator.
The PEAK-Rules package provides multiple dispatch with a syntax similar to the above example. It was later replaced by PyProtocols.
The Reg library also supports multiple and predicate dispatch.
Emulating multiple dispatch
C
C does not have dynamic dispatch, so it must be implemented manually in some form. Often an enum is used to identify the subtype of an object. Dynamic dispatch can be done by looking up this value in a function pointer
A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function poin ...
branch table
In computer programming, a branch table or jump table is a method of transferring program control (Branch (computer science), branching) to another part of a program (or a different program that may have been dynamically loaded) using a table of b ...
. Here is a simple example in C:
typedef void (*CollisionCase)(void);
void collision_AA(void) ;
void collision_AS(void) ;
void collision_SA(void) ;
void collision_SS(void) ;
typedef enum Thing;
CollisionCase collisionCases HING_COUNTTHING_COUNT] = ;
void collide(Thing a, Thing b)
int main(void)
With the C Object System library, C does support dynamic dispatch similar to CLOS. It is fully extensible and does not need any manual handling of the methods. Dynamic message (methods) are dispatched by the dispatcher of COS, which is faster than Objective-C. Here is an example in COS:
#include
#include
#include
// classes
defclass (Asteroid)
// data members
endclass
defclass (Spaceship)
// data members
endclass
// generics
defgeneric (_Bool, collide_with, _1, _2);
// multimethods
defmethod (_Bool, collide_with, Asteroid, Asteroid)
// deal with asteroid hitting asteroid
endmethod
defmethod (_Bool, collide_with, Asteroid, Spaceship)
// deal with asteroid hitting spaceship
endmethod
defmethod (_Bool, collide_with, Spaceship, Asteroid)
// deal with spaceship hitting asteroid
endmethod
defmethod (_Bool, collide_with, Spaceship, Spaceship)
// deal with spaceship hitting spaceship
endmethod
// example of use
int main(void)
C++
, C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
natively supports only single dispatch, though adding multi-methods (multiple dispatch) was proposed by Bjarne Stroustrup
Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, most notable for the invention and development of the C++ programming language. As of July 2022, Stroustrup is a professor of Computer Science at Columbia University. ...
(and collaborators) in 2007. The methods of working around this limit are analogous: use either the visitor pattern
In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to ...
, dynamic cast or a library:
// Example using run time type comparison via dynamic_cast
struct Thing ;
struct Asteroid : Thing ;
struct Spaceship : Thing ;
or pointer-to-method lookup table:
#include
#include
#include
class Thing ;
class Asteroid: public Thing ;
class Spaceship: public Thing ;
Thing::CollisionHandlerMap Thing::collisionCases;
const std::uint32_t Asteroid::cid = typeid(Asteroid).hash_code();
const std::uint32_t Spaceship::cid = typeid(Spaceship).hash_code();
void Asteroid::initCases()
void Spaceship::initCases()
int main()
The ''YOMM2'' library[yomm2](_blank)
Fast, Orthogonal Open Multi-Methods for C++ by Jean-Louis Leroy. provides a fast, orthogonal implementation of open multimethods.
The syntax for declaring open methods is inspired by a proposal for a native C++ implementation. The library requires that the user registers all the classes used as virtual arguments (and their sub-classes), but does not require any modifications to existing code. Methods are implemented as ordinary inline C++ functions; they can be overloaded and they can be passed by pointer. There is no limit on the number of virtual arguments, and they can be arbitrarily mixed with non-virtual arguments.
The library uses a combination of techniques (compressed dispatch tables, collision free integer hash table) to implement method calls in constant time, while mitigating memory usage. Dispatching a call to an open method with a single virtual argument takes only 15–30% more time than calling an ordinary virtual member function, when a modern optimizing compiler is used.
The Asteroids example can be implemented as follows:
#include
#include
class Thing ;
class Asteroid : public Thing ;
class Spaceship : public Thing ;
register_classes(Thing, Spaceship, Asteroid);
declare_method(void, collideWith, (virtual_, virtual_));
define_method(void, collideWith, (Thing& left, Thing& right))
define_method(void, collideWith, (Asteroid& left, Asteroid& right))
define_method(void, collideWith, (Asteroid& left, Spaceship& right))
define_method(void, collideWith, (Spaceship& left, Asteroid& right))
define_method(void, collideWith, (Spaceship& left, Spaceship& right))
int main()
Stroustrup mentions in ''The Design and Evolution of C++'' that he liked the concept of multimethods and considered implementing it in C++ but claims to have been unable to find an efficient sample implementation (comparable to virtual functions) and resolve some possible type ambiguity problems. He then states that although the feature would still be nice to have, that it can be approximately implemented using double dispatch or a type based lookup table as outlined in the C/C++ example above so is a low priority feature for future language revisions.
D
, as do many other object-oriented programming languages, D natively supports only single dispatch. However, it is possible to emulate open multimethods as a library function in D. The ''openmethods'' library[openmethods](_blank)
Open Multi-Methods for D by Jean-Louis Leroy. is an example.
// Declaration
Matrix plus(virtual!Matrix, virtual!Matrix);
// The override for two DenseMatrix objects
@method
Matrix _plus(DenseMatrix a, DenseMatrix b)
// The override for two DiagonalMatrix objects
@method
Matrix _plus(DiagonalMatrix a, DiagonalMatrix b)
Java
In a language with only single dispatch, such as Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
, multiple dispatch can be emulated with multiple levels of single dispatch:
interface Collideable
class Asteroid implements Collideable
class Spaceship implements Collideable
Run time instanceof
checks at one or both levels can also be used.
Support in programming languages
Primary paradigm
* Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
Supporting general multimethods
* C# 4.0
* Cecil
Cecil may refer to:
People with the name
* Cecil (given name), a given name (including a list of people and fictional characters with the name)
* Cecil (surname), a surname (including a list of people with the name)
Places Canada
*Cecil, Alberta, ...
* Clojure
Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is comm ...
* Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
(via the Common Lisp Object System
The Common Lisp Object System (CLOS) is the facility for object-oriented programming which is part of ANSI Common Lisp. CLOS is a powerful dynamic object system which differs radically from the OOP facilities found in more static languages such as ...
)
* Dylan
* Elixir
ELIXIR (the European life-sciences Infrastructure for biological Information) is an initiative that will allow life science laboratories across Europe to share and store their research data as part of an organised network. Its goal is to bring t ...
* Fortress
A fortification is a military construction or building designed for the defense of territories in warfare, and is also used to establish rule in a region during peacetime. The term is derived from Latin ''fortis'' ("strong") and ''facere'' ...
* Groovy
''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context.
History
The ...
* Lasso
A lasso ( or ), also called lariat, riata, or reata (all from Castilian, la reata 're-tied rope'), is a loop of rope designed as a restraint to be thrown around a target and tightened when pulled. It is a well-known tool of the Spanish an ...
* Nim, up to v0.19.x (from v0.20.0 it is necessary to pass a compiler flag)
* Raku
* R
* Seed7
Seed7 is an extensible general-purpose programming language designed by Thomas Mertes. It is syntactically similar to Pascal and Ada. Along with many other features, it provides an extension mechanism. Daniel Zingaro"Modern Extensible Languages" ...
* TADS
Text Adventure Development System (TADS) is a prototype-based domain-specific programming language and set of standard libraries for creating interactive fiction (IF) games.
History
The original TADS 1 was released by High Energy Software as ...
* VB.Net
Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visua ...
via late binding, also via .Net DLR
* Wolfram Language
The Wolfram Language ( ) is a general multi-paradigm programming language developed by Wolfram Research. It emphasizes symbolic computation, functional programming, and rule-based programming and can employ arbitrary structures and data. It is ...
via symbolic pattern matching
Xtend
ref>
Via extensions
* Any .NET language (via the librar
MultiMethods.NET
* C (via the librar
C Object System
* C# (via the librar
multimethod-sharp
* C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
(via the librar
yomm2
multimethods
an
omm
* D (via the librar
openmethods
* Factor
Factor, a Latin word meaning "who/which acts", may refer to:
Commerce
* Factor (agent), a person who acts for, notably a mercantile and colonial agent
* Factor (Scotland), a person or firm managing a Scottish estate
* Factors of production, suc ...
(via the standar
multimethods vocabulary
* Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
(using the extensio
MultiJava
* JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
(via packag
@arrows/multimethod
* Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
(via the modul
Class::Multimethods
* Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
(vi
PEAK-Rules
RuleDispatch
gnosis.magic.multimethods
PyMultimethods
o
multipledispatch
* Racket (vi
multimethod-lib
* Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
(via the librar
The Multiple Dispatch Library
an
Multimethod Package
an
Vlx-Multimethods Package
* Scheme A scheme is a systematic plan for the implementation of a certain idea.
Scheme or schemer may refer to:
Arts and entertainment
* ''The Scheme'' (TV series), a BBC Scotland documentary series
* The Scheme (band), an English pop band
* ''The Schem ...
(via e.g
TinyCLOS
* TypeScript
TypeScript is a free and open source programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are ...
(via packag
@arrows/multimethod
See also
* Predicate dispatch
References
External links
*
*{{cite web , url=https://docs.racket-lang.org/multimethod/ , title=Dynamic multiple dispatch , website=docs.racket-lang.org , access-date=2018-03-12
Articles with example C code
Articles with example C++ code
Articles with example D code
Articles with example Java code
Articles with example Julia code
Articles with example Lisp (programming language) code
Articles with example Python (programming language) code
Method (computer programming)
Polymorphism (computer science)