🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Multiple Dispatch

Multiple dispatch means one function name can have several methods, and Julia picks the method that matches the type of the argument. Each method handles one type.

Two methods share one name

Each line defines describe for one type. Julia runs the method that matches each call.

describe(x::Int) = "a whole number"
describe(x::String) = "some text"

println(describe(7))
println(describe("hello"))

The argument type picks the method

A whole number call runs the first method and a decimal call runs the second. Division always gives a decimal, so the last call runs the second method too.

kind(x::Int) = "whole"
kind(x::Float64) = "decimal"

println(kind(3))
println(kind(3.5))
println(kind(6 / 2))

A third method adds a new type

This name has methods for a whole number, a string, and a character. Each call prints the label from its own method.

message(x::Int) = "number " * string(x)
message(x::String) = "word " * x
message(x::Char) = "letter " * string(x)

println(message(5))
println(message("hi"))
println(message('x'))

Example

function greet(x::String)
    return "Hello, " * x
end

greet(x::Int) = "Number " * string(x)
greet(x::Float64) = "Decimal " * string(x)

println(greet("Ana"))
println(greet(42))
println(greet(2.5))

Key points

  • Method: one version of a function, written for a specific argument type.
  • Same name: several methods can share a single function name.
  • Annotation: :: followed by a type in the argument list says which type a method handles.
  • Choice: Julia picks the method by looking at the type of the value in the call.
  • Adding methods: a program grows by adding a new method, and the existing methods stay as they are.

In this example, greet starts as one method for a String, written in the long form. Two more methods are then added under the same name for a whole number and a decimal. Each call runs the method that matches the type of its argument.

Note

Growing a program by adding methods is a common pattern in Julia code.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

A name has methods for Int, String, and Float64 arguments. Which method runs for the call with the value "hi"?