Types and Dispatch
Last updated on 2025-02-10 | Edit this page
Overview
Questions
- How does Julia deal with types?
- Can I do Object Oriented Programming?
- People keep talking about multiple dispatch. What makes it so special?
Objectives
- dispatch
- structs
- abstract types
Parametric types will only be introduced when the occasion arises.
Julia is a dynamically typed language. Nevertheless, we will see that knowing where and where not to annotate types in your program is crucial for managing performance.
In Julia there are two reasons for using the type system:
- structuring your data by declaring a
struct
- dispatching methods based on their argument types
Inspection
You may inspect the dynamic type of a variable or expression using
the typeof
function. For instance:
OUTPUT
Int64
OUTPUT
String
(plenary) Types of floats
Check the type of the following values:
3
3.14
6.62607015e-34
6.6743f-11
6e0 * 7f0
Int64
Float64
Float64
Float32
Float64
Structures
Multiple dispatch (function overloading)
OUTPUT
Point2(0, 1)
OOP (Sort of)
Julia is not an Object Oriented language. If you feel the unstoppable urge to implement a class-like abstraction, this can be done through abstract types.
JULIA
abstract type Vehicle end
struct Car <: Vehicle
end
struct Bike <: Vehicle
end
bike = Bike()
car = Car()
function direction(v::Vehicle)
return "forward"
end
println("A bike moves: $(direction(bike))")
println("A car moves: $(direction(car))")
function fuel_cost(v::Bike, distance::Float64)
return 0.0
end
function fuel_cost(v::Car, distance::Float64)
return 5.0 * distance
end
println("Cost for riding a bike for 10km: $(fuel_cost(bike, 10.0))")
println("Cost for driving a car for 10km: $(fuel_cost(car, 10.0))")
OUTPUT
A bike moves: forward
A car moves: forward
Cost for riding a bike for 10km: 0.0
Cost for driving a car for 10km: 50.0
An abstract type cannot be instantiated directly:
OUTPUT
ERROR: MethodError: no constructors have been defined for Vehicle
The type `Vehicle` exists, but no method is defined for this combination of argument types when trying to construct it.
Key Points
- Julia is fundamentally a dynamically typed language.
- Static types are only ever used for dispatch.
- Multiple dispatch is the most important means of abstraction in Julia.
- Parametric types are important to achieve type stability.