Zoom Multiple dispatch

Last updated: January 12, 2023

 Table of contents

Concepts

Dynamic dispatch

Functions can be polymorphic (multiple versions exist with the same name).

Dynamic dispatch is the process of selecting one version of a function at run time.

Single dispatch

The choice of version is based on a single object.

This is typical of object-oriented languages such as Python, C++, Java, Smalltalk, etc.

Multiple dispatch

The choice of version is based on the combination of all operands and their types.

This the case of Lisp and Julia.

In Julia, the versions of a function are called methods.

Methods

Julia uses multiple dispatch: functions can have several methods. When that is the case, the method applied depends on the types of all the arguments passed to the function (rather than only the first argument as is common in other languages).

methods(+)

You can see that + has 208 methods!

Methods can be added to existing functions.

Try to understand the following example:
abssum(x::Int64, y::Int64) = abs(x + y)
abssum (generic function with 1 method)
abssum(x::Float64, y::Float64) = abs(x + y)
abssum (generic function with 2 methods)
abssum(2, 4)
6
abssum(2.0, 4.0)
6.0
abssum(2, 4.0)
LoadError: MethodError: no method matching abssum(::Int64, ::Float64)
Closest candidates are:
  abssum(::Int64, ::Int64) at In[2]:1
  abssum(::Float64, ::Float64) at In[3]:1
What could you do if you wanted the last expression to work?

Comments & questions