Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Julia Methods and Multiple Dispatch

Julia Methods and Multiple Dispatch

Multiple Dispatch Method Selection Diagram

Multiple dispatch is the most core language feature of Julia: the same function can define multiple implementations (methods) for different combinations of argument types, and at call time thetypes of all argumentsare used to select the most matching implementation.

This differs from traditional object-oriented languages: method dispatch in C++, Java, and Python looks only at the first argument (the this object), while Julia's functions do not belong to any type and dispatch considers all arguments.


The Relationship Between Functions and Methods

In Julia,a function is a name, and a method is a concrete implementation. Multiple methods can be attached to the same function name:

Example

Method 1: two Float64 arguments

julia

f

(

x::

Float64

, y::

Float64

)

= 2x + y

f

(

generic

function

with

1

method

)

Method 2: two Number arguments (more general)

julia

f

(

x::

Number

, y::

Number

)

= 2x - y

f

(

generic

function

with

2

methods

)

At call time Julia chooses the method that best matches the argument types:

Example

julia

f

(

2.0

,

3.0

)

   

Matches method 1 (Float64, Float64)

7.0

julia

f

(

2

,

3.0

)

     

Does not match method 1, falls back to method 2

1.0

julia

f

(

2

,

3

)

1

Throws a MethodError when the types satisfy no method

julia

f

(

"a"

,

"b"

)

ERROR: MethodError: no method matching f

(

::

String

, ::

String

)

The built-in methods() function can list all methods of a function:

Example

julia

methods

(

f

)

2 methods for generic function "f":

[

1

]

f

(

x::

Float64

, y::

Float64

)

in

Main at REPL

[

1

]

:

1

[

2

]

f

(

x::

Number

, y::

Number

)

in

Main at REPL

[

2

]

:

1

Core functions in Julia Base have a large number of methods; for example the + function has more than 180 methods, handling addition for various types.


Rules of Method Dispatch

Dispatch selects the **most specific** method. If two methods are each no more specific than the other, that is method ambiguity, and Julia reports an error rather than choosing randomly:

Example

julia

g

(

x::

Float64

, y

)

= 2x + y

g

(

generic

function

with

1

method

)

julia

g

(

x, y::

Float64

)

= x + 2y

g

(

generic

function

with

2

methods

)

julia

g

(

2.0

,

3

)

     

Clearly matches the first

7.0

julia

g

(

2.0

,

3.0

)

   

Both methods match and neither is more specific -> ambiguity error

ERROR: MethodError: g

(

::

Float64

, ::

Float64

)

is ambiguous.

Candidates

:

  g

(

x, y::

Float64

)

  g

(

x::

Float64

, y

)

The solution is to add a more specific method for the ambiguous combination of arguments:

Example

julia

g

(

x::

Float64

, y::

Float64

)

= 2x + 2y

g

(

generic

function

with

3

methods

)

julia

g

(

2.0

,

3.0

)

10.0


Parametric Methods

Using where lets a method take effect only when the argument types satisfy some condition:

Example

Matches only when the two argument types are exactly the same

julia

same_type

(

x::T, y::T

)

where

{

T

}

=

true

same_type

(

generic

function

with

1

method

)

julia

same_type

(

x, y

)

=

false

same_type

(

generic

function

with

2

methods

)

julia

same_type

(

1

,

2

)

true

julia

same_type

(

1

,

2.0

)

false

Type parameters can also carry constraints

julia

same_type_numeric

(

x::T, y::T

)

where

{

T

<

:

Number

}

=

true

same_type_numeric

(

generic

function

with

1

method

)

The most common use of parametric methods is to constrain both the container and the element type at once:

Example

Can only append Int to an Int vector

julia

myappend

(

v::

Vector

{

T

}

, x::T

)

where

{

T

}

=

[

v..., x

]

myappend

(

generic

function

with

1

method

)

julia

myappend

(

[

1

,

2

,

3

]

,

4

)

4

-element

Vector

{

Int64

}

:

 

1

 

2

 

3

 

4

julia

myappend

(

[

1

,

2

,

3

]

,

4.5

)

ERROR: MethodError: no method matching myappend

(

::

Vector

{

Int64

}

, ::

Float64

)


Interface Design Based on Abstract Types

Combining multiple dispatch with abstract types lets you write "abstract-oriented" code: write generic methods for abstract types and specialized methods for concrete types.

Example

Abstract shape

julia

abstract

type

Shape

end

julia

struct Circle

<

: Shape

           r::

Float64

       

end

julia

struct Rect

<

: Shape

           w::

Float64

           h::

Float64

       

end

Generic method: any Shape can compute its area, dispatched type by type

julia

area

(

c::Circle

)

= pi

c.

r

^

2

area

(

generic

function

with

1

method

)

julia

area

(

r::Rect

)

= r.

w

r.

h

area

(

generic

function

with

2

methods

)

A fallback method can also be placed on the abstract type

julia

describe

(

s::Shape

)

=

"area is $(area(s))"

describe

(

generic

function

with

1

method

)

julia

describe

(

Circle

(

1

)

)

"area is 3.141592653589793"

julia

describe

(

Rect

(

2

,

3

)

)

"area is 6.0"

Tip:This is "object orientation" in Julia: there is no concept of classes and inherited methods; polymorphism is achieved with "abstract types + methods dispatched by type", and it is more flexible than traditional OOP, adding a new Shape subtype requires no changes to any existing code, just add an area method for it.


Operators Are Functions Too

In Julia most operators are essentially functions, so operators can be overloaded for custom types:

Example

julia

1

2

3

6

julia

(

1

,

2

,

3

)

     

The function form of an operator

6

julia

f = +          

Operators can be passed as values

f

(

singleton

type

of

function

+, subtype of

Function

)

julia

f

(

1

,

2

)

3

Overload the + operator for a custom type:

Example

julia

import

Base: +      

Extending Base functions requires import first

julia

struct Vec2

           x::

Float64

           y::

Float64

       

end

julia

Base.:+

(

a::Vec2, b::Vec2

)

= Vec2

(

a.

x

x

, a.

y

y

)

julia

Vec2

(

1

,

2

)

(

3

,

4

)

Vec2

(

4.0

,

6.0

)


Type Piracy (Don't Do This)

Addingtypes from someone else's moduleExtendfunctions from someone else's moduleis called type piracy, for example defining a Base * method for Base's Symbol type. This globally changes the behavior of other code and causes hard-to-trace bugs, so it must be avoided:

Example

Dangerous example, do not imitate!

module

Bad

   

import

Base.

   

(

x::

Symbol

, y::

Symbol

)

=

Symbol

(

x, y

)

 

Type piracy

end

A legal extension only needs to satisfy "at least one side is defined by yourself": either extend a Base function for your own package's type (like overloading + for Vec2 above), or add a method for a Base type to your own function.


Common Patterns in Method Design

Fallback method + promote pattern

The classic way the standard library handles mixed types: first write a fast method for same types, then use promote to convert different types to a common type and forward:

Example

The concrete method handles same types

julia

area

(

multiplier::

Float64

, x::

Float64

)

= multiplier

x

area

(

generic

function

with

1

method

)

Fallback method: promote the arguments to a common type and call again

julia

area

(

multiplier, x

)

= area

(

promote

(

multiplier, x

)

...

)

area

(

generic

function

with

2

methods

)

julia

area

(

2

,

3.0

)

   

Int and Float64 are promoted to Float64

6.0

Orthogonal Design

When there are many argument combinations, rather than writing N x M methods, normalize to one type with a conversion function:

Example

Do not write 4 combination methods, write 1 + 1 conversion

f

(

x::A, y::A

)

= ...

f

(

x, y

)

= f

(

toA

(

x

)

, toA

(

y

)

)

   

toA converts any type to A


Practical Advice for Using method

Recommendation Description
Prefer wide argument types over narrow ones Write Integer instead of Int64, to be compatible with types like BigInt
Resolve ambiguities early Define the ambiguity-resolving method first to avoid ambiguity errors in intermediate states
Avoid dispatching on abstract container element types f(::Vector{Int}) Such signatures easily cause ambiguities with other packages; use f(::Vector{<:Real}) or do not annotate the element type
Write a fallback method for interface functions Write a generic implementation on the abstract type so subtypes work out of the box