Trusted answers to developer questions

Definition: Multiple dispatch

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

svg viewer

What is multiple dispatch?

When writing a piece of code, it is inevitable to make certain functions, and t is usually a good programming practice to name the functions to match their functionality. For example, if you are making a function to join two strings, you might consider naming it string_concat or add_string.

Often, multiple functions are essentially doing the same thing with a little bit of change. Is it possible to keep the name of all these functions similar? Yes, possible using multiple dispatch.

Multiple dispatch is a feature supported by some programming languages that allows you to create multiple functions with the same name. The multiple forms of branching from the same function name are called methods. Below is a list of languages that support multiple dispatch.

Method of Support Programming Language
Built-in multiple dispatch C#, Common Lisp, Julia, Raku
Multiple dispatch libraries Python, JavaScript
Emulating multiple dispatch C, C++, D, Java

Example

Let’s look at how multiple dispatch works using Julia:

function concat_this(a::AbstractString, b::AbstractString)
return a*" "*b
end
function concat_this(a::Real, b::AbstractString)
return string(a)*" "*b
end
function concat_this(a::AbstractString, b::Real)
return a*" "*string(b)
end
function concat_this(a::Real, b::Real)
return string(a)*" "*string(b)
end
println(concat_this("abra", "kadabra"))
println(concat_this("123", "kadabra"))
println(concat_this("abra", "456"))
println(concat_this("123", "456"))
println(methods(concat_this))

The code above has three methods of a function named concat_this.

Usually, if we make one function for it then we might face problems when we concatenate strings with numbers. Therefore, we made four functions to cater for all the possible concatenations between strings and numbers. Now, we can go ahead and call concat_this, pass a string or number as either the first or second argument, and get a concatenated string back. Moreover, we can look at the list of function’s methods using the methods() method of Julia.

RELATED TAGS

multiple dispatch
methods
modularity

CONTRIBUTOR

Shahpar Khan
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?