In Chapter 2, Defining Functions, we introduced the concept of multiple dispatch in Julia, which is deeply integrated into the language. Here, we will extend the same topic to cover types.
To have a quick look at what multiple dispatch means in functions, here is the same code for a function that prints out the cube of a number:
julia> function calculate_cube(num::Int64)
return num ^ 3
end
calculate_cube (generic function with 1 method)
julia> function calculate_cube(num::Float64)
return num ^ 3
end
calculate_cube (generic function with 2 methods)
# 2 methods for generic function "calculate_cube":
calculate_cube(num::Float64) at REPL[1]:2
calculate_cube(num::Int64) at REPL[1]:2
julia> calculate_cube(10)
1000
julia> calculate_cube(10.10)
1030.301
Here, the function supported both kinds of concrete types (which are Int64
and Float64
) values. One gave an integer output and the other gave Float
type output.
But how can...