CodeToLive

Julia Types & Multiple Dispatch

Understand Julia's type system and multiple dispatch.

Type Hierarchy

# Julia type hierarchy
Any
├── Number
│   ├── Real
│   │   ├── AbstractFloat
│   │   ├── Integer
│   │   │   ├── Signed
│   │   │   └── Unsigned
│   │   └── Rational
│   └── Complex
└── AbstractString

Defining Types

# Abstract type
abstract type Shape end

# Concrete type
struct Circle <: Shape
    radius::Float64
end

# Mutable struct
mutable struct Point
    x::Float64
    y::Float64
end

Multiple Dispatch

# Define methods for different types
area(s::Circle) = π * s.radius^2
area(s::Rectangle) = s.width * s.height

# Julia will choose the correct method based on types
c = Circle(2.0)
area(c)  # 12.566...

Parametric Types

# Generic type
struct Box{T}
    content::T
end

# Create instances with different types
b1 = Box(42)       # Box{Int64}
b2 = Box("Julia")  # Box{String}

Type Unions

# Function accepting either Int or Float
function process(x::Union{Int, Float64})
    println("Processing number: $x")
end
← Back to Tutorials